jQuery jquery点击事件传播

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2244320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:05:50  来源:igfitidea点击:

Jquery click event propagation

jqueryeventsclick

提问by ozsenegal

I have a table with click events bound to its rows (<tr>). There are <a>elements inside those rows with their own click events assigned.

我有一个表格,点击事件绑定到它的行 ( <tr>)。<a>这些行中的元素分配了自己的点击事件。

Problem is, when i click on the <a>element, it also fires the click event from the parent <tr>. I don't want this behavior; I just want to fire the <a>click event.

问题是,当我点击<a>元素时,它也会从父元素触发点击事件<tr>。我不想要这种行为;我只想触发<a>点击事件。

Code:

代码:

 // Event row TR

 $("tr:not(:first)").click(function() {
    $(".window, .backFundo, .close").remove();

    var position = $(this).offset().top;
    position = position < 0 ? 20 : position;

    $("body").append( $("<div></div>").addClass("backFundo") );
    $("body").append( $("<div></div>").addClass("window")
         .html("<span class=close><img src=Images/close.png id=fechar /></span>")
      .append( "<span class=titulo>O que deseja fazer?</span>"
              +"<span class=crud><a href=# id=edit>Editar</a></span>"
              +"<span class=crud><a href=# id=delete codigo=" 
              + $(this).children("td:first").html() 
              + ">Excluir</a></span>" )
       .css({top:"20px"})
       .fadeIn("slow") );

    $(document).scrollTop(0);
 });

 // <A> Element event

 $("a").live("click",function() { alert("clicked!"); });

Whenever you click the anchor it fires event from it parent row. Any ideas?

每当您单击锚点时,它都会从其父行触发事件。有任何想法吗?

回答by rahul

You have to stop event bubbling. In jQuery you can do this by

你必须停止事件冒泡。在 jQuery 中,您可以通过

e.stopPropagation();

in the onclick event of the anchor tag.

在锚标签的 onclick 事件中。

$("a").live("click",function(e){alert("clicked!");e.stopPropagation();});

Edit

编辑

See this post

看到这个帖子

jquery Event.stopPropagation() seems not to work

jquery Event.stopPropagation() 似乎不起作用

回答by Antony Hatchkins

I would use bindinstead of livefor both <tr>and <a>and the following code

我将使用bind而不是live用于<tr><a>和以下代码

$("a").bind("click", function(e){ alert("clicked!"); e.stopPropagation() });

$("a").bind("click", function(e){ alert("clicked!"); e.stopPropagation() });

for <a>.

<a>

All <a href>'s will work as expected and <tr>event handler code won't execute after clicking <a>.

所有<a href>的都将按预期工作,并且<tr>在单击后不会执行事件处理程序代码<a>

Works in all modern browsers.

适用于所有现代浏览器。