递归添加单击事件处理程序
Adding click event handlers recursively
我有一个元素#standardBox
#standardBox.click --> replaces itself with #newBox
#newBox.click --> replaces itself with #standardBox
但是这个最新的#standardBox
没有点击事件监听器。我希望它有一个点击事件监听器和随后创建的元素。这进入了一个递归循环,我不知道如何解决这个问题。
我将此用于具有标准内容的标头,它将被一些中间/新内容所取代,这也是为了回到标准内容。。。
谢谢。
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
});
});
http://codepen.io/anon/pen/YPLKLq
将处理程序附加到主体,如下所示:
$("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
元素。
使用以下代码。使用"点击"功能动态创建的元素不触发事件。您需要将处理程序附加到文档(正文)
$(document).on('click','#standardBox',function(){
$('#container').html('<div id="newBox"></div>');
// register event handler for new element created
});
$(document).on('click','#newBox',function(){
$('#container').html('<div id="standardBox"></div>');
// but this #standardBox has no click event listener
});
为什么要写这么复杂的代码来做这件事。因为可能有一个非常简单的代码。
让我们说这是你的html。
<div id="container">
<div id="standardBox"></div>
</div>
现在,要更改内部容器。
$(function(){
$('#container div').click(function(){
$(this).attr("id")=="standardBox"?$(this).attr("id","newBox"):$(this).attr("id","standardBox");
});
});
相关文章:
- keyup事件处理程序更改焦点不适用于快速键入
- 提示使用服务器端事件处理程序激活JavaScript
- 将事件处理程序绑定到任何可能的事件
- 正在将事件处理程序添加到不存在的类
- 在循环中附加事件处理程序时出现浏览器性能问题
- 在同一个javascript事件处理程序中调用不同的函数
- 有没有一种方法可以让内联事件处理程序在元素创建后立即执行
- 检查事件处理程序参数
- 实现延迟的jquery更改事件处理程序
- 如何使用Node.js在JavaScript模块文件之间使用事件处理程序
- 如何使jQuery的“bind”或“on”事件处理程序幂等
- 带有参数的Javascript事件处理程序
- Jquery事件处理程序仅适用于匿名函数
- 如何从另一个处理程序内部取消JavaScript事件处理程序函数的执行
- 如何在jQuery事件处理程序中存储和重用超时
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 异步处理所有事件处理程序的方法
- jsplumb中的Click事件处理程序丢失“;这个“;对象
- 构造函数中的事件处理程序与构造函数外的事件处理函数的行为不同
- 如何在事件处理程序的回调中防止Default