3

I create my Html elements using java script createElement().But I cannot select any of the html elements in JQuery -- $("p").on("click",function(){}) . It works for $(document) though. My JQuery script is at the end of the body in the html page. But when inspect elements is checked in the browser after page creation html elements are below the scripts.

I have seen there many other similar questions but none of them worked. Please help me solve this I have been working on this for couple of days now and its taking me no where.

4

2 回答 2

10

对于动态创建的元素,请使用:

$(document).on('click', 'p', function(){
    console.log("clicked");
});

jsFiddle 演示,展示了在创建元素之前分配点击事件。

于 2013-06-11T06:38:17.600 回答
0

使用live而不是on.

$("p").live("click",function(){}

编辑:

不推荐使用 of live,我们可以使用on ,但要从文档中工作,而不是从元素中工作。

利用:

$(document).on( 'click', '.someClass', doSomething);

代替:

$('.someClassParent').on( 'click', '.someClass', doSomething);

于 2013-06-11T06:39:32.190 回答