[英]event.stopPropagation() is not working in jQuery event handler
在我的 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"
现在选择器与search-person
类不匹配checkboxes
。
这是一个完整的例子:
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);
}
});
我遇到了类似的问题并在使用时修复了它
$(selector).click(function(){ ... })
代替
$(context).on("click", selector, function(){ ... });
做这个:
$(context).on("click", ".search-person .ui-checkbox .ui-btn", function(e) {
//toggle checkbox
this.checked = !this.checked;
//don't change page
e.stopPropagation();
});
怎么样:
e.preventDefault();
您可能还需要从处理程序返回 false。
我用这个 hack 解决了它:
$(context).on("click", ".search-person", function(e) {
if (!e.hasOwnProperty('_clickedName')) {
var id = $(this).attr("data-id");
PROFILE_MODULE.getProfile(id);
}
});
$(context).on("click", ".search-person .ui-checkbox .ui-btn", function(e) {
e['_clickedName'] = true;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.