将事件处理程序添加到运行时创建的DOM树中的特定子级

Adding an event handler to a specific children within a DOM tree that is created on runtime

本文关键字:DOM 添加 程序 运行时 创建 事件处理      更新时间:2023-09-26

我正在尝试将事件处理程序绑定到DOM树中的一个子元素,该元素在运行时添加到HTML动态中。下面的HTML显示了我得到的内容。该表及其thead和tbody是静态HTML。稍后我将添加tbody(<tr><td><img src="bla.png"></td></tr>)的内容。

<table id="progData">
    <thead>
        <th>Image</th>
    </thead>
    <tbody>
        <tr><td><img src="bla.png"></td></tr>
    </tbody>
</table>

所以现在我想在图像上绑定一个事件处理程序,比如:

$("#progData").on("click", "img", function(e){/*do sth in here*/});

但由于某种原因,这并不奏效。我必须使用

$("#progData").on("click", "tr", function(e){/*do sth in here*/});

以使其至少在单击行时工作。

有没有任何方法可以将事件绑定到DOM中比直接子元素更深的动态元素?

啊,对不起。我在事件处理程序中的回调函数中出现了一个错误。由于在访问一些只存在于"tr"中的属性之前,我必须使用"tr"。因此,当我将处理程序更改为"img"对象时,我只是忘记了现在通过parent()函数访问属性…:/

所以这只是我的错误。问题已解决:)

您可以尝试执行-

$("#progData").find("img").on("click", function(e){/*do sth in here*/});

如果在命中代码之前已经加载了HTML。

您可以尝试在动态内容中添加一个类,然后绑定它的点击事件,如

HTML-

<tr><td><img class="jMyImage" src="bla.png"></td></tr>

Javascript-

$(".jMyImage").on("click", function(e){/*do sth in here*/});

我猜您正试图将事件附加到一个仍然不存在的标记。我的意思是,您应该检查在插入表行的时刻之后添加事件侦听器的时刻。例如,这对我有效:

var onImageLoaded = function() {
    $("#progData").on("click", "img", function(e){
        if(e.currentTarget.tagName == 'IMG') {
            console.log("clicked");
        }
    })
}
var table = $("#progData");
table.find("tbody").html("<tr><td><img src='"http://krasimirtsonev.com/blog/articles/CSSThePowerOfInherit/icon-bullet.jpg'" onload='"javascript:onImageLoaded();'"></td></tr>");

JSFiddle->http://jsfiddle.net/krasimir/ybavx/

如果我理解正确,这应该是你想要的:

$(document).on("click", "#progData img", function(e){/*do sth in here*/});

或者如果你只想要第一个:

$(document).on("click", "#progData img:nth-child(2)", function(e){/*do sth in here*/});

由于元素是动态添加的,您需要附加到文档中,因为元素尚未创建或是在文档创建后创建的。更多信息可在此处找到:http://api.jquery.com/on/