[英]Check input[type=checkbox] in jQuery event handler
我有以下HTML:
<ul id=list>
<li>
<input type=checkbox />
Item 1
</li>
<li>
<input type=checkbox />
Item 2
</li>
<li>
<input type=checkbox />
Item 3
</li>
</ul>
以及相應的Javascript:
$('ul').bind('click', function(e) {
if (e.srcElement.tagName.toLowerCase() === 'input') {
e.srcElement.checked = true;
}
return false;
});
$('body').bind('click', function() {
alert('you should see this alert if and only if you did NOT click the list');
})
當我單擊一個復選框時,它不會被選中。 我希望在用戶單擊它時對其進行檢查。
我如何做到這一點,以便在用戶單擊復選框時將其選中,但仍取消body
單擊事件處理程序?
我也寫了一個JS小提琴 。
編輯:我知道代碼有點笨拙,但是對於應用程序,它需要以這種方式進行結構化,因此解決方案應盡可能接近原始代碼。 話雖如此,對所觀察到的行為的解釋將是可理解的。
使用e.stopPropagation()
[docs]而不是return false
。 后者還可以防止發生默認操作,即切換復選框的狀態。
您還應該考慮將事件處理程序綁定到change
事件,而不是click
,這不是切換復選框的唯一方法。 不過,您仍然需要添加其他處理程序以防止click
事件冒泡。
為了避免單擊冒泡,您需要使用event.stopPropagation()取消冒泡,我注意到stopPropagation()應該是函數中的第一件事。
$('ul').bind('click', function(e){ e.stopPropagation(); if (e.target.tagName.toLowerCase() === 'input') { e.target.checked = true; } }); $('body').bind('click', function() { alert('you should see this alert if and only if you did NOT click the list'); });
我想這就是你想要的嗎?
$('ul').bind('click', function(e) {
e.stopPropagation();
});
$('body').bind('click', function() {
alert('you only see this alert if and only if you did NOT click the list');
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.