2014-08-31 57 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