jQuery .hide() doesn't run on dynamically created elements [duplicate]

感情迁移 提交于 2021-01-29 20:59:45

问题


I want to dynamically create some div elements in my container. I do it with simple function:

function myFunction(volume){
for(var i = 1; i<= volume; i++){
$('.container').append("<div></div>");
}

The problem is that generated div elements does NOT react to my jQuery .hide() function. Does anyone know why it is not working? HTML looks fine for both manualy and dynamically created elements.

I did jsfiddle, but it is kinda broken too: http://jsfiddle.net/gQBen/

My call of .hide() function

$('div').mouseenter(function() {
if (run){
$(this).hide(3000, function() {
result++;
run = false;
rewrite();
});
}
});

Aron solve it in comments: http://jsfiddle.net/arunpjohny/SM38C/1/ thanks!


回答1:


you should use event delegation for that

$(".container").on("mouseenter","div",function(e){

});

Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.




回答2:


Use .onchange() instead of onclick in the option

$('select').on('change',function(){
myFunction(this.value);
});

also add value to the options

<option value="4" >4</option>

You'll also need to use event-delegation on dynamically added elements

$(document).on('mouseenter','div',function() {

DEMO




回答3:


UPDATE

The question was updated so

$(".container").on("mouseenter","div",function(e){
   if (run){
       $(this).hide(3000, function() {
          result++;
          run = false;
          rewrite();
       });
   }
});


来源:https://stackoverflow.com/questions/22612263/jquery-hide-doesnt-run-on-dynamically-created-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!