如何添加也接受參數的事件偵聽器(addEventListener(),attachEvent())?如何將自定義參數傳遞給JavaScript中的事件偵聽器?
的參數作爲像元素的自定義屬性傳遞:
<img src="icon.gif" alt="Test button" command="test" />
<img src="icon2.gif" alt="Test button2" command="write" />
如何添加也接受參數的事件偵聽器(addEventListener(),attachEvent())?如何將自定義參數傳遞給JavaScript中的事件偵聽器?
的參數作爲像元素的自定義屬性傳遞:
<img src="icon.gif" alt="Test button" command="test" />
<img src="icon2.gif" alt="Test button2" command="write" />
你可以使用這樣的事情:
element.addEventListener ('click', (function (myParam) {
return function() {
// user myParam here
};
}) (yourParam), false);
無論你傳遞什麼「yourParam」將通過「myParam」參數訪問事件處理程序...
你可以在你的處理器使用的getAttribute,像
var param = this.getAttribute('command');
它不起作用 – samuel 2009-12-09 12:34:36
這工作對我來說: attachEvent('onclick',function(){ linkClicked(link.getAttribute (「命令」)); },false); – samuel 2009-12-09 12:55:36