javascript - event.stopPropagation() 在 jQuery 事件处理程序中不起作用

标签 javascript jquery jquery-mobile jquery-events event-propagation

在我的 jQuery 移动应用程序中,我有这段代码

$(context).on("click", ".search-person", function() {
    var id = $(this).attr("data-id");
    PROFILE_MODULE.getProfile(id);
});

$(context).on("click", ".search-person .ui-checkbox .ui-btn", function(e) {
    //toggle checkbox
    $(this).click();
    //don't change page
    e.stopPropagation();
});

.search-person 是表格行,.search-person .ui-checkbox .ui-btn 是一行中列中的复选框。

如果我单击该复选框,我不希望触发行单击事件。但是在这段代码中,它在 e.stopPropagation() 运行后仍然执行,有什么问题吗?

最佳答案

e.stopPropagation(); 实际上停止了事件的传播,但是它没有阻止的是 $(context).on("click", ".search- person", function() {}); 从调用其处理程序开始,它们是截然不同的不同事件。

您可以通过向匹配 tr 的选择器添加元素类型条件来解决此问题:

"tr.search-person"

现在选择器不匹配 checkboxessearch-person 类。

这是一个完整的例子:

var context = $('table');

$(context).on("click", "tr.search-person", function() {
  alert('row');
});

$(context).on("click", ".search-person.ui-checkbox.ui-btn", function(e) {
  alert('check box');
  // this.click(); will also work but why bother 
  // if all you are doing is clearing the checkbox
  $(this).prop('checked', !$(this).prop('checked'));
  e.stopPropagation();
});
tr.search-person {
  background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr class="search-person">
    <td>Click Here and the Check Box</td>
    <td>
      <input class="search-person ui-checkbox ui-btn" type="checkbox">
    </td>
  </tr>
  <tr class="search-person">
    <td>Click Here and the Check Box</td>
    <td>
      <input class="search-person ui-checkbox ui-btn" type="checkbox">
    </td>
  </tr>
</table>

或者,您可以检查触发事件的元素类型:

$(context).on("click", ".search-person", function() {
    if ($(this).is('tr')) {
        var id = $(this).attr("data-id");
        PROFILE_MODULE.getProfile(id);
    }
});

关于javascript - event.stopPropagation() 在 jQuery 事件处理程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29041314/

相关文章:

javascript - 是否可以在幻灯片容器内移动 Orbit 子弹?

php - 来自 mysql/JSON 的 twitter bootstrap typeahead 源代码

jquery - 鉴于这些要求,我应该如何构建我的 HTML5 list ?

jquery-mobile - 通过JS添加Font Awesome图标

javascript - 如何使用值数组作为参数发出原型(prototype) ajax 请求?

javascript - 选择中的渲染选项失败

javascript - 处理和返回多个 promise

jquery - 拖放图像,返回错误的尺寸

android - jQuery Mobile 中的 taphold 卡住

javascript - 将 javascript 函数分配给 dom 元素