回调函数不适用于JQuery添加的元素。在我的示例中,有一个父分区和class=parent
。点击它后,<span class="child">Child</span>
正在被添加。但是当我点击孩子时,它不会提示消息。请参考下面如何将回调函数添加到由JQuery添加的元素
<html>
<head>
<style>
.parent{
width: 50px;
height: 30px;
line-height: 30px;
background-color: #232323;
color: #fff;
text-align: center;
}
.child{
width: 50px;
height: 30px;
line-height: 30px;
background-color: #f3b556;
color: #232323;
text-align: center;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="parent">
<span>Parent</span>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('.parent').click(function(){
alert('parent clicked');
$(this).after("<span class='child'>child</span>");
});
$('.child').click(function(){
alert('child clicked');
});
</script>
</body>
</html>
您需要使用'.on'而不是.click。看看这个答案http://stackoverflow.com/a/1207393/1270865 – cafebabe1991