我正在使用jQuery創建自定義單選按鈕,並且出現問題。 當點擊與無線電相關的標籤時,點擊事件觸發兩次,如果我只點擊收音機本身,它工作正常(實際上它不是我點擊的收音機,而是包裝整個輸入和標籤的div)。下面是代碼:jQuery單擊標籤時點擊兩次點擊
的HTML:
<div id="box">
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>RADIO1</asp:ListItem>
<asp:ListItem>RADIO2</asp:ListItem>
<asp:ListItem>RADIO3</asp:ListItem>
</asp:RadioButtonList>
</div>
的jQuery:
<script type="text/javascript">
$(function() {
$('#box').find('input:radio').each(function (i) {
var input = $(this);
// get the associated label using the input's id
var label = $('label[for=' + input.attr('id') + ']');
// wrap the input + label in a div
$('<div class="custom-radio"></div>').insertBefore(input).append(label, input);
var wrapperDiv = input.parent();
// find all inputs in this set using the shared name attribute
var allInputs = $('input[name=' + input.attr('name') + ']');
// necessary for browsers that don't support the :hover pseudo class on labels
label.hover(
function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover checkedHover');
});
//bind custom event, trigger it, bind click,focus,blur events
wrapperDiv.bind('updateState', function() {
if ($(this)[0].children[1].checked) {
allInputs.each(function() {
var curDiv = $('div > label[for=' + $(this).attr('id') + ']').parent();
curDiv.removeClass('custom-radio-checked');
curDiv.addClass('custom-radio');
});
$(this).toggleClass('custom-radio custom-radio-checked');
}
else {
$(this).removeClass('custom-radio-checked checkedHover checkedFocus');
}
})
.trigger('updateState')
.click(function() { console.log('click'); })
.focus(function() {
label.addClass('focus');
}).blur(function() {
label.removeClass('focus checkedFocus');
});
});
});
</script>
是否有此行爲的任何解決方案?
爲什麼會發生這種情況? – chovy
因爲有嵌套的項目。層次結構中的每個項目都會引發事件。 – Jordan
如果你使用它作爲一個複選框,這也是我需要使輸入實際上被檢查:'jQuery('input')。prop('checked',true);' –