将 onclick 事件添加到 javascript 动态创建的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8446109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:02:28  来源:igfitidea点击:

adding onclick event to javascript dynamically created element

javascript

提问by Ali_dotNet

I'm dynamically adding labels to my table when user selects combo box items, but also I want these dynamically added labels to be erasable when user clicks on them, here is my javascript function:

当用户选择组合框项目时,我正在向我的表格中动态添加标签,但我也希望这些动态添加的标签在用户点击它们时可以擦除,这是我的 javascript 函数:

    function OnSelectedIndexChange()

{
    if (document.getElementById('cmbDestinationUser').selectedIndex != 0) {
        var spanTag = document.createElement("span");
        spanTag.id = "span1";
        var e = document.getElementById("cmbDestinationUser");
        var strUser = e.options[e.selectedIndex].text;
        spanTag.innerHTML = strUser;
        var TR = document.createElement('tr');
        var TD = document.createElement('td');
        TD.appendChild(spanTag);
        TR.appendChild(TD);
        document.getElementById('tblReceivers').appendChild(TR);
    }
    document.getElementById('cmbDestinationUser').selectedIndex = 0;
}

should I add onclick to spantag? how can I do so? should I create another function for erasing or can I define the remove operation in this function thanks

我应该将 onclick 添加到 spantag 吗?我该怎么做?我应该创建另一个擦除功能还是可以在此功能中定义删除操作,谢谢

回答by RightSaidFred

Yes, add the onclick to the span:

是的,将 onclick 添加到span

spanTag.onclick = function() {
    this.innerHTML = '';
};

This just clears the content of the span. I wasn't sure exactly what you meant by "erasing".

这只是清除span. 我不确定你所说的“擦除”到底是什么意思。

If you wanted to remove the spanentirely, do this:

如果您想span完全删除,请执行以下操作:

spanTag.onclick = function() {
    this.parentNode.removeChild( this );
};


To remove the row, do this:

要删除该行,请执行以下操作:

spanTag.onclick = function() {
    var el = this;
    while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );

    if( el )
        el.parentNode.removeChild( el );
};

Or to make it a little clearer perhaps:

或者让它更清楚一点:

spanTag.onclick = function() {
    var el = this.parentNode;
    while( el ) {
       if( el.nodeName.toLowerCase() === 'tr' ) {
           el.parentNode.removeChild( el );
           break;
       }
       el = el.parentNode;
    } 
};

回答by Munter

You should really use event delegation instead of setting an event handler on each node you create.

您应该真正使用事件委托,而不是在您创建的每个节点上设置事件处理程序。

This way you can assign a single event handler to the table around the table rows, which handles all clicks on all rows and removes that row. You set it once only.

通过这种方式,您可以为表格行周围的表格分配一个事件处理程序,该处理程序处理所有行上的所有点击并删除该行。您只需设置一次。

table.onclick = function (e) {
    var target = e.target || window.event.srcElement;

    while (target.nodeName !== 'TR') {
        target = target.parentNode;
    }
    target.parentNode.reamoveChild(target);
}