我有一个div,当按下时会添加另一个具有相同类的div。但是当我点击动态添加的元素时,没有任何反应。
$('.container').on('click', function(){
var newColumn = $('<li class="column"/>');
var newState = $('<div class="container" unselectable="on">Nothing</div>');
newState.appendTo(newColumn);
newColumn.appendTo($('#canvas'));
});
&#13;
.container{
border:1px solid black;
width:100px;
height:40px;
text-align:center;
vertical-align:middle;
line-height:40px;
border-radius:10px;
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
}
.column{
list-style-type: none;
display:inline;
width:100px;
float:left;
margin:10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="canvas">
<li class="column">
<div class="container" unselectable="on">
works
</div>
</li>
</ul>
&#13;
如何让点击事件适用于所有元素?
答案 0 :(得分:5)
由于您的脚本会自动创建.container
元素,因此您必须使用事件委派 on()
来处理新的DOM:
$('body').on('click', '.container', function(){
//Your code here
});
希望这有帮助。
$(document).on('click', '.container', function(){
var newColumn = $('<li class="column"/>');
var newState = $('<div class="container" unselectable="on">Nothing</div>');
newState.appendTo(newColumn);
newColumn.appendTo($('#canvas'));
});
&#13;
.container{
border:1px solid black;
width:100px;
height:40px;
text-align:center;
vertical-align:middle;
line-height:40px;
border-radius:10px;
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
}
.column{
list-style-type: none;
display:inline;
width:100px;
float:left;
margin:10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="canvas">
<li class="column">
<div class="container" unselectable="on">
works
</div>
</li>
</ul>
&#13;