2014-10-20 103 views
0

我是jQuery或JavaScript的初學者。我想知道是否有寫多個元素和多個函數的點擊事件。jquery on()多元素和多功能

例如,我有很多按鈕可以在點擊時執行不同的功能。 是否有包含1點擊事件中的所有功能?像「單擊文件」,「button1」將做「功能...」,「button2」將做「功能...」。

更像一個開關盒樣式??

+0

那麼你需要單獨定義每個功能,你可以有數據屬性每個按鈕元素,接下來你可以工作一個單擊事件處理程序的所有:如果您要添加和動態刪除按鈕他們仍然可以被委派按鈕 – 2014-10-20 08:09:57

+0

謝謝@GeorgeGarchagudashvili爲您及時回覆,我確實找到了1個類似的答案,[鏈接](http://codereview.stackexchange.com/questions/18160/different-way-of-writing-multiple-click-functions) ,那是你的意思嗎? – 2014-10-20 08:22:22

+0

是的,確切!很好的發現;)) – 2014-10-20 08:23:51

回答

1

可能這樣做,是的,但它不是最佳實踐。它看起來像這樣:

$(document).on("click", "button", function() { 
    switch (this.id) { // (Or whatever you want to use to differentiate the buttons) 
     case "button1": 
      // Do button1's stuff 
      // ... 
      break; 
     case "button2": 
      // Do button2's stuff 
      // ... 
      break; 
     // ...and so on... 
    } 
}); 

但是使用單獨的處理程序要好得多。

$(document) 
    .on("click", "#button1", function() { // Again, it doesn't have to be an id... 
     // button1's stuff here 
    }) 
    .on("click", "#button2", function() { // ...just whatever differentiates the buttons 
     // button2's stuff here 
    }); 
+1

如果頁面上的元素是靜態的,'$(「#button1」)。on(「click」,function(){''document.ready'裏面會更好。 – Regent 2014-10-20 08:17:51

+0

Thanks @TJ Crowder – 2014-10-20 08:23:44

+0

@Regent,是不是會爲每個按鈕設置1個事件處理程序? – 2014-10-20 08:25:05