【问题标题】:How to stop running the next function?如何停止运行下一个功能?
【发布时间】:2012-05-19 22:03:11
【问题描述】:

我有一个点击顶部<tr> 的事件,然后还有一个点击tr > td > button 的事件。当我点击tr > td > button 时,相关的onclick() 函数正在运行,但是<tr> 上的相关函数也在之前运行。

喜欢:

<tr onclick="run_tr();">
    <td><input type="button" onclick="run_td();" /></td>
</tr>

如何停止通过单击按钮自动呼叫下一个呼叫?

【问题讨论】:

标签: javascript events


【解决方案1】:

在按钮onclick 函数中你需要停止事件冒泡:

event.stopPropagation();

按照您的代码:

HTML:

<input type="button" onclick="run_td( event );" />

JS:

function run_td( event ) {
    if ( event.stopPropagation ) { 
        event.stopPropagation();
    }
    event.cancelBubble = true;
    // ... rest of your code.
}

【讨论】:

  • 不,这是错误的方法...例如阻止浏览器跟踪链接,但不会停止事件传播。
  • @antyrat 我只是在使用它。但是,在顶部&lt;tr&gt; onclick 中有一个alert("hello");。反正这个警报只是刷了一次就消失了。
  • @4lvin 您还需要将event 传递给onclick 属性。在 jsFiddle 上查看我更新的答案和演示 jsfiddle.net/antyrat/5AvKy
【解决方案2】:

您必须使用方法e.stopPropagation() 来停止事件的传播。欲了解更多信息,请查看此链接:http://www.quirksmode.org/js/events_order.html#link9

【讨论】:

  • 对于 OP:记住要同时使用 if (event.stopPropagation) event.stopPropagation()event.cancelBubble = true 来处理 W3C 和 IE 事件模型。
  • 是的,我忘了在回答中提到这一点,但在我链接的页面中有说明
  • 我只是在使用它。但是,在顶部&lt;tr&gt; onclick 中有一个alert("hello");。反正这个警报只是冲了一次就消失了。我不能完全终止它吗??
【解决方案3】:

我不明白为什么你不能使用推荐的方法,这里有一个例子:

<div onclick="alert('div click called');">
  Click here to see div onclick
  <button onclick="
    (event.stopPropagation && event.stopPropagation());
    event.cancelBubble = true;
    alert('stopped click');
  ">Button click but no div click</button>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多