Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
本机javascript中动态生成元素的JQuery on()方法_Javascript_Jquery - Fatal编程技术网

本机javascript中动态生成元素的JQuery on()方法

本机javascript中动态生成元素的JQuery on()方法,javascript,jquery,Javascript,Jquery,我正在使用jQuery查找本例的本机JavaScript代码: $("#parent").on("click", ".child", function(){ alert("clicked"); }); 到目前为止,我所做的工作是处理页面附带的元素,而不是动态生成的元素: var children = document.getElementById("parent").getElementsByClassName("child"); for (var i = 0, l = childre

我正在使用jQuery查找本例的本机JavaScript代码:

$("#parent").on("click", ".child", function(){
    alert("clicked");
});
到目前为止,我所做的工作是处理页面附带的元素,而不是动态生成的元素:

var children = document.getElementById("parent").getElementsByClassName("child");
for (var i = 0, l = children.length; i < l; i++)
{
    children[i].onclick = foo;
}
function foo(el)
{
    alert("child clicked");
}
var children=document.getElementById(“父”).getElementsByClassName(“子”);
for(变量i=0,l=children.length;i
如何使此代码适用于动态生成的元素

如果您正在寻找答案,请点击这里:

您可以执行如下操作,侦听添加到文档中的元素,然后绑定函数。我还建议绑定一个事件侦听器,而不是将您的方法分配给
onclick
属性,但请查看您真正需要的:

    // listen for new elements being added to the document
    document.addEventListener('DOMNodeInserted', function(event) {
        // check if they're the type of node you're looking for
        if (event.relatedNode.querySelectorAll('your selector')) {
            // bind the event listener
            event.relatedNode.addEventListener('click', function(event) {
                // your code
            });
        }
    });

确保在生成动态内容后设置了
子变量
。否则它将是
null
@Mahi谢谢我以重复的方式关闭了问题IDK为什么有人否决了一个问题我自己关闭了它-_-