我正在用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;
}

09-11 06:51