2014-02-06 79 views
1

我在check box上使用了一些JQ的東西,即使父母div被點擊。我正在切換check box的值。點擊div工作正常,但當你點擊複選框時,該功能被調用兩次。有什麼辦法可以解決這個問題嗎?下面是我的代碼(Fiddle) HTML:如何停止jQuery中的事件冒泡?

<div class="check-unit"> 
    <input type="checkbox" class="check" /> 
    <p class="brandList">Model</p> 
</div> 

JQ:

$('.check').on('change',function(e){ 
    e.stopImmediatePropagation(); 
    if($(this).is(':checked')){ 
     console.log("checked"); 
    }else{ 
     console.log("unchecked"); 
    } 
}); 

$('.check-unit').on('click',function(e){ 
    var checkbox = $(this).children('.check'), 
    chhhk= checkbox.attr('checked') ? false : true; 
    checkbox.attr('checked',chhhk); 
    $(this).children('.check').change(); 
}); 

我已經看到了stackoverfloweventbubbling問題,但仍然感到困惑如何做到這一點。 FIDDLE

+1

你可以做多種方式,'event.stopPropagation ()'或'event.stopImmediatePropagation()'或簡單地'event.preventDefault()' – Praveen

+1

**注意:**使用'.prop()'而不是'.attr'作爲布爾屬性值 – Anton

+1

@Praveen'preventDefault'和'stopPropagation'完全不同,不可互換 – tborychowski

回答

1

只有當目標不是輸入

$('.check').on('change',function(e){ 
    if(this.checked){ 
     console.log("checked"); 
    }else{ 
     console.log("unchecked"); 
    } 
}); 

$('.check-unit').on('click',function(e){ 
    if (! $(e.target).hasClass('check')) { 
     $(this).children('.check').prop('checked', function(_,state) { 
      return !state; 
     }).trigger('change'); 
    } 
}); 

FIDDLE

一點題外話執行父元素的回調,這是label元素是!

+0

+1 n冰,但爲什麼'event.stopPropagation()'在這種情況下不起作用的任何原因? – Praveen

+2

但是當點擊'p'''''''不會和'e.target'一樣,所以它會起作用 –

+0

@ArunPJohny - 沒有,但這不是OP要求的嗎?我意識到'p'可能是問題的一部分,但問題是特別要求點擊'div',所以我爲此寫了一些東西,只是有點挑剔。改變它與'p'一起工作。 – adeneo

0

您需要使用.prop()而不是.attr()來設置checked屬性。

$('.check').on('change', function (e) { 
    if (this.checked) { 
     console.log("checked"); 
    } else { 
     console.log("unchecked"); 
    } 
}).click(function (e) { 
    //prevent clicks in the checksboxes from bubbling up otherwise when you click on the checkbox the state will get toggled again the event will be bubbled to check-unit which will again toggle the state negating the click 
    e.stopPropagation() 
}); 
$('.check-unit').on('click', function() { 
    var checkbox = $(this).children('.check'), 
     //use .is() and checked-selector to check whether the checkbox is checked 
     chhhk = checkbox.is(':checked'); 
    //use .prop() instead of .attr() & toggle the checked state 
    checkbox.prop('checked', !chhhk).change(); 
}); 

演示:Fiddle

0

您可以檢查,如果你正在改變之前點擊複選框。

$('.check-unit').on('click', function (e) { 
    if (!($(e.target).hasClass('check'))) { 
     var checkbox = $(this).children('.check'), 
      chhhk = checkbox.prop('checked'); 
     checkbox.prop('checked', !chhhk).change(); 
    } 
}); 

還要注意的是代碼而不是使用ATTR道具,因爲當你使用布爾屬性值,你應該使用.prop()

DEMO