我有一堆<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){...
节省了几行字,但是又能怎样我确实做得很好,很干净并且有最佳做法?有没有一个更好的模式呢?
一个的jsfiddle是[这里](http://jsfiddle.net/spaceninja/9nc7mu4h/) – SpaceNinja 2014-08-31 23:53:37