在我的 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"
现在选择器不匹配 checkboxes
与 search-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/