取消特定元素上的事件冒泡 - javascript
基本上,我想单击页面上除输入字段和一个块级元素(扩展为其中的所有子元素)之外的任何位置,删除所述输入字段。所以我在整个文档上放置了一个 onclick 事件。为了保持上述条件,我在明确的指示之前添加了条件,仅当事件不是由特定元素引起时才执行此操作。
clearSearch = function (e){ e ? e : e = window.event; e.target ? target = e.target : target = e.srcElement; if (target.nodeName != "INPUT" && document.getElementById('ul')) document.getElementById('input').value = ""; }
使用此方法,如果我想继续单击 ul 以避免导致该操作,我必须在此 if 语句中明确说明。然后我必须对 ul 下的 li 元素执行相同的操作。然后是我创建的其他孩子。
基本上,这看起来效率很低,我想知道是否有人可以帮助我想出一个更好的解决方案来解决我为自己造成的混乱。
Basically, I want to make clicking anywhere on a page except in an input field and on one block level element (an by extension all children there in) erase said input field. So I put an onclick event on the whole document. To keep the conditions above I put conditions before the clear instructions to only do it if the event did not arise from specific elements.
clearSearch = function (e){ e ? e : e = window.event; e.target ? target = e.target : target = e.srcElement; if (target.nodeName != "INPUT" && document.getElementById('ul')) document.getElementById('input').value = ""; }
With this method if I want to keep clicking on the ul from causing the action I have to explicitly state it in this if statement. Then I have to do the same for the li elements under the ul. Then any other children I create.
Basically this seems really inefficient and I was wondering if someone could help me out in thinking up a better solution to this mess I have created for myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从
clearSearch
中删除复杂的逻辑,然后清除搜索框。然后向您不想调用此方法的元素添加一些新的 onClick 处理程序。在这些处理程序中,将 event.cancelBubble 设置为 true 以防止调用clearSearch 函数。来自 quirksmode:
You can remove the complex logic from
clearSearch
and just have it clear the search box. Then add some new onClick handlers to the elements you don't want to call this method. In those handlers setevent.cancelBubble
to true to prevent the clearSearch function being called.From quirksmode: