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

时间:2014-08-31 23:50:57

标签: jquery button each

我有一堆<button>,当你点击它们时它们都需要去。我确信我可以使用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;
    });
});

技术上它起作用,但我觉得我应该这样做:

$.each(websiteButtons, function(buttonName,buttonLoc){...

而不是:

$.each(websiteButtons, function(i,e){...

保存几行,但我能做些什么才能使它变得干净整洁?这有改进模式吗?

1 个答案:

答案 0 :(得分:1)

它保持不变,两者都有效