我有一堆<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