2013-04-05 3 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

시도 대신 이렇게 (당신이 사업부를 만들 때 클릭 이벤트를 첨부)하는이 모든 코드가 jQuery를에 있어야

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

보십시오. –

+2

이 답변을 바탕으로 [jsfiddle] (http://jsfiddle.net/kBZfS/)을 확인하십시오. –

+0

@Y, hm, yea kinda *;) –

1

을 준비된. 문제는 요소가 작성되기 전에 이벤트가 바인딩되는 것입니다.

$(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를 숨길 것이다. –

관련 문제