admin管理员组文章数量:1325236
Tho this question has been asked before, and the answer is this:
$('#container').on('click','#dynamicElement', function(){ /* the code */ });
The code above will find the #dynamicElement
when its being clicked on.
But what if there is no click, nor any other event?
Suppose the following scenario:
$.ajax(
url:'file.php',
data: {'param':'value'},
success: function(response){
/*
how would I get #dynamicElement if it was not click on?
the element had no event fired at all, nor had any of its parennt
containers.
Now what?
*/
}
);
Tho this question has been asked before, and the answer is this:
$('#container').on('click','#dynamicElement', function(){ /* the code */ });
The code above will find the #dynamicElement
when its being clicked on.
But what if there is no click, nor any other event?
Suppose the following scenario:
$.ajax(
url:'file.php',
data: {'param':'value'},
success: function(response){
/*
how would I get #dynamicElement if it was not click on?
the element had no event fired at all, nor had any of its parennt
containers.
Now what?
*/
}
);
Share
Improve this question
edited Oct 10, 2015 at 21:41
Zakaria Acharki
67.5k15 gold badges78 silver badges106 bronze badges
asked Oct 10, 2015 at 21:34
KarandawovKarandawov
931 silver badge8 bronze badges
2
-
It looks like you want to get the element inside the success callback by using the normal jquery selector
$('#dynamicElement')
– filype Commented Oct 10, 2015 at 21:36 -
I suppose it IS as easy as
$('#dynamicElement')
, i had always avoided doing that, as i though i knew it would not ever work – Karandawov Commented Oct 10, 2015 at 21:45
2 Answers
Reset to default 4If your new element is being added to the page inside the success
callback,
at that point you can call $('#dynamicElement')
Using $('#dynamicElement')
anywhere outside of the callback would not return the element since it had not been added to the DOM yet.
How event binding works is as long as that element is in the DOM itself, you can access it by writing a selector like the following:
$('#dynamicElement')
The reason you need event delegation is when you dynamically create the elements after you bound the event. Then, when the event is fired, it looks through all the children of the element you bound it to to find if there are any elements matching your selector.
However, if you know that the element has already been appended to the DOM, you can bind it directly without event delegation, and access it through finding it by ID.
If it hasn't yet, there is no way for you to manipulate it as it doesn't exist yet.
本文标签: javascriptjQueryFind dynamically created element without eventsStack Overflow
版权声明:本文标题:javascript - jQuery - Find dynamically created element without events - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742166270a2425882.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论