我有一个元素#standardBox
#standardBox.click --> 用#newBox 替换自己
#newBox.click --> 用#standardBox 替换自己
但是这个最新的#standardBox
没有点击事件监听器。我希望它有一个点击事件监听器及其随后创建的元素。这进入了一个递归循环,我不知道如何解决。
我将其用于具有标准内容的 header ,它被一些中间/新内容所取代,这又是为了回到标准内容......
谢谢。
HTML
<div id="container">
<div id="standardBox"></div>
</div>
CSS
html, body {
margin: 0;
padding: 0;
height: 100%;
}
#container {
position: relative;
height: 5em;
width: 5em;
background: #C5CAE9;
}
#standardBox {
position: absolute;
top: 20%;
right: 20%;
bottom: 20%;
left: 20%;
background: #ffffff;
cursor: pointer;
}
#newBox {
height: 3em;
width: 3em;
background: #000000;
cursor: pointer;
}
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('#standardBox').click(function(){
$('#container').html('<div id="newBox"></div>');
// register event handler for new element created
$('#newBox').click(function(){
$('#container').html('<div id="standardBox"></div>');
// but this #standardBox has no click event listener
});
});
最佳答案
像这样将处理程序附加到主体:
$("body").on("click", "#standardBox", function(){
$('#container').html('<div id="newBox"></div>');
})
.on("click", "#newBox", function(){
$('#container').html('<div id="standardBox"></div>');
});
这会导致正文监听来自 #standardBox
和 #newBox
的事件。请注意,this
变量仍设置为 #standardBox
或 #newBox
元素。
关于javascript - 递归添加点击事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28644673/