有什么问题?
我正在动态创建jQuery div,但它无效!
<body>
<a id="main">Add DIV</a>
<div id="parent"></div>
<script>
$(function(){
var count = 0;
$('#main').click(function(){
$("<div />", {id: "new" + count})
.append(count)
.appendTo($('#parent'));
count++;
});
});
$("#new3").click(function(){
alert("new3 clicked!");
});
</script>
</body>
还有其他方法吗?
答案 0 :(得分:1)
您必须使用.on更改.click,因为click事件附加到文档准备好后创建的元素。
$(document).on('click','#new3',function(){ ... });
答案 1 :(得分:0)
$(function(){
var count = 0; // counter for elements
var on_click_added=false; // boolan if click function exist
$('#main').click(function(){
$("<div />")
.html('div id=>new'+count) //add html code for clarity
.attr('id', 'new' + count) //add id attribute
.appendTo($('#parent'));
count++;
if(($('#new3').length>0)&&(!on_click_added)){ //add on click function if element exist and not added early
$('#new3').click(function(){
alert("new3 clicked!");
});
on_click_added=true;
}
});
});
div{
margin: 10px;
border-style:solid;
border-width:1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="main">Add DIV</a>
<div id="parent"></div>