简体   繁体   English

Javascript 同时点击 2 个元素打开和关闭 html 标签

[英]Javascript 2 elements are clicked same time open and close a html tag

i have a html div tag which gets opened with a onclick event.我有一个 html div 标签,它通过 onclick 事件打开。 in this div tag is another html i tag which also have a onclick event for closing the div tag.在这个 div 标签中是另一个 html i 标签,它也有一个 onclick 事件用于关闭 div 标签。 The problem is of course now that the div tag gets always open because the close button is inside the div tag which works same time as a open button, ok just have a look to my code to make it easyer:问题当然是现在 div 标签总是打开的,因为关闭按钮在 div 标签内,它与打开按钮同时工作,好吧,看看我的代码让它更容易:

<div onclick="OpenElement(1)">Element 1
<div id="element1">
  <i onclick="CloseElement(1)">&ensp;</i>
  <h2>Element</h2>
</div>
</div>

<script>
function OpenElement(nr)
{
 var elementnr="element"+nr;
 document.getElementById(elementnr).style.display  = 'block';
}

function CloseElement(nr)
{
 var elementnr="element"+nr;
 document.getElementById(elementnr).style.display  = 'none';
}
</script>

The question is now how must i code it that it works correctly, the div tag must get open when i click on it and it must get close only when you click the close button?现在的问题是我必须如何对其进行编码以使其正常工作,当我单击它时 div 标签必须打开,并且只有当您单击关闭按钮时它才必须关闭?

I think you should use stopPropagation in your CloseElement function ( https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation )我认为您应该在CloseElement function ( https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation )中使用stopPropagation

It will stop the event from bubbling up to your enclosing div with the OpenElement function.它将使用OpenElement function 阻止事件冒泡到您的封闭div

You must stop the event propagation, as by default the event propagates up the DOM tree to its parent.您必须停止事件传播,因为默认情况下事件会向上传播 DOM 树到其父级。

 function OpenElement(nr){ var elementnr="element"+nr; document.getElementById(elementnr).style.display = 'block'; alert("open"); } function CloseElement(nr){ var elementnr="element"+nr; document.getElementById(elementnr).style.display = 'none'; alert("close") } function closeEvent(event){ event.stopPropagation(); CloseElement(1); }
 <div onclick="OpenElement(1)"> Element 1 <div id="element1"> <i onclick="closeEvent(event)">&ensp; close</i> <h2>Element</h2> </div> </div>

Click on the child element also triggers click on its parent.单击子元素也会触发对其父元素的单击。 This is event propagation.这是事件传播。

To avoid this, you have to stop propagation manually.为避免这种情况,您必须手动停止传播。 (See Event.stopPropagation ) (见Event.stopPropagation

 function parentClick(e) { alert("Parent Click"); } function childClick(e) { alert("child click"); e.stopPropagation(); }
 div { cursor: pointer; border: 1px solid black; padding: 10px; }
 <div onclick="parentClick(event)">Parent Element <div onclick="childClick(event)">Child Element</div> </div>

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

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