2013-04-05 37 views
2

我創建了一個基於li元素數量創建div的腳本,該部分工作正常。現在我想要做的是隱藏這些div的(動態創建),但它不起作用。有人能告訴我我在這裏做錯了嗎?謝謝!!
Fiddle here如何隱藏我動態創建的div?

我的代碼:

$(document).ready(function(){ 
$(".create").click(function(){ 
i=''; 
var count = $("li").length; 
for(var i=0;i<count;i++){ 
$('<div class="mydiv" style="width:100px;height:100px;background-color:red;border:1px solid #000000;"></div>').appendTo('body'); 
} 
}); 

$('.check').click(function(){ 
var getDivs= $('div').length; 
alert(getDivs); 
}); 
//Why is this not working? 
$('div').click(function(){ 
$(this).hide(); 
}); 
}); 

回答

3

嘗試這樣做,而不是(當你創建DIV附加的單擊事件):

$('<div class="mydiv" style="width:100px;height:100px;background-color:red;border:1px solid #000000;"></div>') 
.click(function(){ 
$(this).hide(); 
}) 
.appendTo('body'); 
+0

這是最好的答案。 – 2013-04-05 23:49:09

+2

看看這個[jsfiddle](http://jsfiddle.net/kBZfS/)根據這個答案。 – 2013-04-06 00:04:18

+0

@Y,hm,yea kinda s *;) – 2013-04-06 00:05:35

1

所有這些代碼應該是jQuery的準備。問題是你的事件在元素被創建之前被綁定。

$(document).ready(function(){ 
    $(".create").click(function(){ 
     i=''; 
     var count = $("li").length; 

     for(var i=0;i<count;i++){ 
      $('<div class="mydiv" style="width:100px;height:100px;background-color:red;border:1px solid #000000;"></div>').appendTo('body'); 
     } 
     $('.check').click(function(){ 
      var getDivs= $('div').length; 
      alert(getDivs); 
     }); 
     //Now working 
     $('div').click(function(){ 
      $(this).hide(); 
     }); 
    }); 
}); 
0

嘗試

$(document).on('click', 'div', function() { 
$(this).hide(); 
)}; 
+0

這將隱藏**你點擊每個** div,在頁面上 – 2013-04-05 23:48:17