Ajax调用连续发生2次



我有一个我无法理解的展示行为的导轨应用程序。我有一个html文件:

<h1>Hello World</h1>
  <table>
    <tr>
        <td>Hello</td>
    </tr>
    <tr>
        <td>Hello</td>
    </tr>
    <tr>
        <td>Hello</td>
    </tr>
    <tr>
        <td>Hello</td>
    </tr>
</table>

i然后有一个JavaScript(确实是jQuery)文件,当有人单击表中的一行时,我会击中该文件。

$(document).ready(function(){
  $("tr", "table").click(function(){
    console.log("TEST");
  });
});

每次我单击表中的一行时,该功能都会称为2次。我两次在控制台中获得"测试"。我是JQuery和Rails的新手,所以我知道我缺少一些简单的东西。有人请告诉我我做错了什么。

它正在计算" TR"one_answers" Table"

的点击

尝试

$(document).ready(function(){
  $("tr").click(function(){
    console.log("TEST");
  });
});

正如他们所说的,这是因为每个TR都在表中,所以这是正确的行为。如果您想避免它,我相信防止事件宣传会起作用:

$(document).ready(function(){
  $("tr", "table").click(function(e){
    e.stopPropagation();
    console.log("TEST");
  });
});

启动桌子的点击点击,然后单击tr,请尝试以下

$(document).ready(function(){
  $("tr").click(function(){
    console.log("TEST");
  });
});

您不需要单击表上的单击事件,除非您想单击表格 - 但不能连续单击,这听起来不正确

最新更新