Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   почему не кликабельные производные от append (https://javascript.ru/forum/dom-window/49393-pochemu-ne-klikabelnye-proizvodnye-ot-append.html)

imedia 11.08.2014 14:37

почему не кликабельные производные от append
 
Здравствуйте посмотрите пожалуйста этот код
такое впечатление что объекты с классом child_cnt2 не появились,
при клике на них (красный цвет) их класс не отображается
почему?
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js "></script>
</head>
<body>
<style>
.parent_cnt{
width:100px;
height:200px;
background:#eee;
}
.child_cnt{
width:100px;
height:50px;
background:#ee9;
border:1px solid #333;
cursor:pointer;
}
.child_cnt2{
width:100px;
height:50px;
background:red;
border:1px solid #333;
cursor:pointer;
}
</style>
<div class="parent_cnt">
<div class="child_cnt"></div>
<div class="child_cnt"></div>
</div>
<script>
$('div').click(function(){
alert($(this).attr('class'))
});
</script>
<script>
$('.child_cnt').click(function(){
$('.parent_cnt').empty();
$('.parent_cnt').append('<div class="child_cnt2"></div><div class="child_cnt2"></div>')

});
</script>
</body>
</html>

MallSerg 11.08.2014 14:41

Uncaught ReferenceError: $ is not defined
т.е. для начала не подключен jQuery

WorM32 11.08.2014 14:46

Потому что элементы добавлены после того, как был повешен обработчик.

нужно делать так:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js "></script>
</head>
<body>
<style>
.parent_cnt{
width:100px;
height:200px;
background:#eee;
}
.child_cnt{
width:100px;
height:50px;
background:#ee9;
border:1px solid #333;
cursor:pointer;
}
.child_cnt2{
width:100px;
height:50px;
background:red;
border:1px solid #333;
cursor:pointer;
}
</style>
<div class="parent_cnt">
<div class="child_cnt"></div>
<div class="child_cnt"></div>
</div>
<script>
$(document).on('click', 'div', function(){
alert($(this).attr('class'));
});
</script>
<script>
$('.child_cnt').click(function(){
$('.parent_cnt').empty();
$('.parent_cnt').append('<div class="child_cnt2"></div><div class="child_cnt2"></div>')

});
</script>
</body>
</html>


Часовой пояс GMT +3, время: 17:46.