【问题标题】:Clickable Container with inner links带有内部链接的可点击容器
【发布时间】:2017-11-23 05:20:34
【问题描述】:

如果这已经存在,我深表歉意,但我找不到类似的东西。我的愚蠢问题是:

我有一个带有链接的可点击容器,看起来有点像:

<div onclick="someFunction()">
    <...>
    <...>
    <button onclick="otherFunction()">
</div>

我希望能够单击容器中的任何位置并打开一些东西,但我也希望能够使内部的按钮工作。感谢您提前提供的所有帮助,并对愚蠢的问题表示歉意。

【问题讨论】:

  • 所以你想说每当你点击容器中的任何地方都会出现一个带有按钮的div?

标签: javascript html onclick containers


【解决方案1】:

它会像你的想法一样工作,当你点击按钮时,点击会在你的按钮和 div check codepen 上触发

event.stopPropagation()

var someFunction = function(event){
  alert('<someFunction>');
  
}

var otherFunction = function(event){
  alert("otherFunction ->");
}

var otherFunctionStopPropagation = function(event){
  alert("|otherFunction|");
  event.stopPropagation();
}
.Some{
  height:200px;
  background-color:yellow;
  z-index:1;
  
}

.other{
  z-index:2;
}
<div onclick="someFunction()" class="Some">
  <button onclick="otherFunction(event)"  class='other' id='other'>otherFunction</button>
  <button onclick="otherFunctionStopPropagation(event)"  class='other' id='other'>otherFunctionStopPropagation</button>

  <a onclick="otherFunctionStopPropagation(event)" href='' class='other' id='other'>a_otherFunctionStopPropagation</a>
</div>

https://codepen.io/mastersmind/pen/EbLEBb

【讨论】:

  • 它确实有效,但你必须阻止事件冒泡到它的父级
  • 另外附注:我怎样才能让它忽略 标签......或者是另一个问题?
  • @ScottWhite 你能详细说明你的意思是忽略吗?
  • @mastermind 基本上我的问题是我的容器内是否有&lt;a href="page2.html"&gt;link&lt;/a&gt; 它仍然调用someFunction() 看起来你调整了你的代码,所以我会试一试并报告.一如既往的感谢!
【解决方案2】:

你应该使用 event.stopPropogation() 函数。这将防止事件冒泡到父元素,

otherFunction() {
  event.stopPropagation()
  // your code here
}

【讨论】:

  • 你打错了,应该是stopPropagation
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多