繁体   English   中英

如何在javascript中仅单击一次后禁用div而不禁用其中的元素的click事件?

[英]How to disable a div after only one click in javascript without disabling click event on elements within it?

我正在尝试在elemId div内的单击上创建一个按钮。 但是希望仅将按钮附加一次,然后仅在div而不是在button元素上禁用click事件。

 document.getElementById('elemId').addEventListener('click', 
   function(e){

   var button = document.createElement("button");
   var buttonText = document.createTextNode("click me");
   button.appendChild(buttonText);
   document.getElementById('elemId').appendChild(button)


   document.getElementById('elemId').removeEventListener('click', 
     function(e){
     // removeEventListener doesn't work
  })

   document.getElementById('elemId').disabled = true 
     // disabled  doesn't work 
  })

的HTML:

<div style="background-color: teal; height: 100px; width: 100px; " id="elemId">Count</div>

您可以将函数命名为任意名称,在本示例中,我将其命名为“ x”,然后在要删除click事件监听器时引用它。

 document.getElementById('elemId').addEventListener('click', function x(e) { var button = document.createElement("button"); var buttonText = document.createTextNode("click me"); button.appendChild(buttonText); document.getElementById('elemId').appendChild(button) document.getElementById("elemId").removeEventListener("click", x); }) 
 <div style="background-color: teal; height: 100px; width: 100px; " id="elemId">Count</div> 

创建函数/处理程序,并在元素创建过程之后使用功能removeEventListener删除该处理程序。

这种方法创建了一个功能来满足您的要求,此外,您将能够恢复该处理程序以再次绑定它。

 document.getElementById('elemId').addEventListener('click', handler); function handler(e) { var button = document.createElement("button"); var buttonText = document.createTextNode("click me"); button.appendChild(buttonText); document.getElementById('elemId').appendChild(button) document.getElementById('elemId').removeEventListener('click', handler); } 
 <div style="background-color: teal; height: 100px; width: 100px; " id="elemId">Count</div> 

您要确保您具有函数处理程序。 由于您没有删除适当的事件侦听器,因此这样做的方式无效。 您正在使用匿名函数,但需要指向用于删除事件的实际函数处理程序。

另外,我不确定您要禁用div会做什么。 我删除了该行,因为您无法禁用div。

我还对代码进行了一些重构,以使代码更清晰,更易于阅读。

 document.getElementById('elemId').addEventListener('click', addButton, false); function addButton() { var button = document.createElement("button"); var buttonText = document.createTextNode("click me"); var clickElement = document.getElementById('elemId'); button.appendChild(buttonText); clickElement.appendChild(button); clickElement.removeEventListener('click', addButton, false); } 
 <div style="background-color: teal; height: 100px; width: 100px; " id="elemId">Count</div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM