2014-08-31 59 views
0

我有一堆<button> s,当你点击它们时,它们都需要去某处。我确信我可以使用jQuery来创建一个对象,并使用一对键/值来指定按钮(键)的类名和它们在单击它们时的URL(值)。但是我很难做对。使用jQuery将点击事件绑定到这些按钮的每个()按钮

// 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){...

节省了几行字,但是又能怎样我确实做得很好,很干净并且有最佳做法?有没有一个更好的模式呢?

+0

一个的jsfiddle是[这里](http://jsfiddle.net/spaceninja/9nc7mu4h/) – SpaceNinja 2014-08-31 23:53:37

回答

1

它仍然是相同的,都将工作的上述

+0

啊,你说得对。上次我尝试时,我必须完成一个typeo,但[它有效](http://jsfiddle.net/spaceninja/9nc7mu4h/19/)。但是,这是否正确?有一种更简单或更好的方式,或者这是完美的。 – SpaceNinja 2014-09-01 00:04:16

+0

不,这是完美的,保持 – Ahmad 2014-09-01 00:56:21