我有一个函数,它在任务结束时将一个按钮分配给一个新的 id。
function altChecker() {
var doc = document,
out = [],
appButton = doc.getElementById('appButton'),
//re = /click-me/gi,
output = doc.createElement('p');
output.setAttribute('id', 'output');
EventUtility.addHandler(appButton, 'click', function(e) {
//I have not included all the function details to concentrate on the question
appButton.id = 'appButtonNextChecker';
var appButtonNextChecker = doc.getElementById('appButtonNextChecker');
nextChecker(appButtonNextChecker);
});
}
function nextChecker(newBtnName) {
EventUtility.addHandler(newBtnName, 'click', function(e) {
$('#output').innerHTML = "";
console.log('next Checker, button!')
});
}
基本上 DOM 中有一个按钮最初分配给 appButton
ID,然后我将其更改为:
appButton.id = 'appButtonNextChecker';
当 altChecker
函数触发时...
然后我将按钮分配给一个新变量,并将该变量传递给下一个函数...
var appButtonNextChecker = doc.getElementById('appButtonNextChecker');
nextChecker(appButtonNextChecker);
虽然我可以在 DOM 中看到按钮的 ID 发生变化,并且我在 nextChecker
函数中看到 console.log
触发,
$('#output').innerHTML = ""; //doesn't fire
altChecker
函数也(再次)触发?!当我重新分配新 ID 时,我不是切断了与 click
功能的连接吗?
如有任何帮助,我们将不胜感激!
最佳答案
Javascript 不记得您最初是通过它的 ID 附加事件的。该事件附加到元素本身,而不是 ID。这不像 CSS。
事实上,您的变量也仍然持有相同的元素,因此在更改 ID 后也无需创建新变量。由于您使用的是 jQuery,因此您只需键入 $(appButton).unbind();
删除事件处理程序。您可能还想查看 .on()
和 .off()
关于javascript - 尽管所有权已更改,但我对按钮的 EventListener 仍继续触发,为什么? (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808565/