我正在用一个 XML 文件填充一个表,我有一个链接到更多详细信息的列。由于我运行网页的方式(Chrome 扩展),我需要在填充表格时动态添加事件处理程序。
我有这个工作...
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("detailLink").addEventListener('click',
clickHandlerDetailLink); });
function clickHandlerDetailLink(e) { detailLinkPress('SHOW'); }
function detailLinkPress(str) {
alert("Message that will show more detail");
}
但是我该如何动态添加事件处理程序呢?我已经为该列中的所有字段分配了 detailLink 的 ID。
最佳答案
您可能需要监听表的突变事件,然后每次检查触发该事件的目标元素。以前它曾经是这些事件“DOMNodeInserted”或“DOMSubtreeModified”,但它们非常慢,因此根据新规范,监听器称为 MutationObserver(比以前的快得多)。这是为我的测试而编辑的一些 Mozilla 网页的示例:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.target.id + ", " + mutation.type +
(mutation.addedNodes ? ", added nodes(" + mutation.addedNodes.length + "): " + printNodeList(mutation.addedNodes) : "") +
(mutation.removedNodes ? ", removed nodes(" + mutation.removedNodes.length + "): " + printNodeList(mutation.removedNodes) : ""));
});
});
// configuration of the observer:
var config = { attributes: false, childList: true, characterData: false };
var element = document.getElementById('TestID');
// pass in the target node, as well as the observer options
observer.observe(element, config);
function printNodeList(nodelist)
{
if(!nodelist)
return "";
var i = 0;
var str = "";
for(; i < nodelist.length; ++i)
str += nodelist[i].textContent + ",";
return str;
}
关于javascript - 在 JavaScript 中动态添加 EventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15077988/