递归添加单击事件处理程序

Adding click event handlers recursively

本文关键字:程序 事件处理 单击 添加 递归      更新时间:2024-02-16

我有一个元素#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");
    });
});