Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jQuery将单击事件绑定到这些按钮的每个()上_Jquery_Button_Each - Fatal编程技术网

使用jQuery将单击事件绑定到这些按钮的每个()上

使用jQuery将单击事件绑定到这些按钮的每个()上,jquery,button,each,Jquery,Button,Each,我有一堆s,当你点击它们时,它们都需要去某个地方。我相信我会喜欢jQuery,只需创建一个对象,其中包含成对的键/值,这些键/值指定按钮的类名(键)以及单击按钮时它们所在的URL(值)。但我很难把它做好 // A lits of button class names and where they go when you click them var websiteButtons = { bmw: "http://www.bmw.com", mercedes: "http://ww

我有一堆
s,当你点击它们时,它们都需要去某个地方。我相信我会喜欢jQuery,只需创建一个对象,其中包含成对的键/值,这些键/值指定按钮的类名(键)以及单击按钮时它们所在的URL(值)。但我很难把它做好

// A lits of button class names and where they go when you click them
var websiteButtons = {
    bmw: "http://www.bmw.com",
    mercedes: "http://www.mercedes.com",
};

// Go through the object, and add behaviors to the buttons
// The key is the button class name, and the value is the URL
// Applied to a click event to go to that URL
$.each(websiteButtons, function(i,e){
    var buttonName = i;
    var buttonLoc = e;
    $('.' + buttonName).on('click', function(){
        window.location = buttonLoc;
    });
});
从技术上讲,这是可行的,但我觉得我应该:

$。每个(网站按钮、函数(按钮名称、按钮链接){…

而不是:

$。每个(网站按钮、函数(即){…


为了节省几行,但是我能做些什么来让它变得漂亮、干净并具有最佳实践?有没有更好的模式呢?

它保持不变,两者都会起作用

上面提到的一点是啊,你是对的。我上一次尝试时一定做过typeo,但是。但这是正确的方法吗?有更简单或更好的方法吗是这样的,还是这很完美不,这很完美,留着吧