2013-10-17 182 views
2


我想觸發一個事件,而不是手動的,但通過jQuery本身。
這裏明白我的問題,更好地:jQuery自動觸發複選框事件

$('.commonCheck').change(function() { 
      if ($(".cashierCheck").attr("checked")) { 
       $('.cashierInput').fadeIn(); 
       console.log("________________hr") 
      } 
      else{ 
       $('.cashierInput').fadeOut(); 
       console.log("_______________uncjecked") 
      } 
} 

我的複選框:

<input type="checkbox" name="cashierFilter" id="cashierFilter" class="cashierCheck commonCheck" class="mrL0" /> 

當我手動檢查/取消選中沒有任何問題被觸發更改事件的複選框。 但我想,當我莫名其妙地執行此要發生的事件:

$('#cashierFilter').prop('checked','true'); 

回答

2

演示http://jsfiddle.net/ga9nn/

您可以使用trigger以編程方式觸發事件:

$('#cashierFilter').prop('checked', true).trigger('change'); 

此外,你應該使用is檢查元素的屬性,並且可以將選擇器緩存在變量中以提高性能:

$('.commonCheck').change(function() { 
    var $cashierCheck = $(".cashierCheck"); 
    if ($cashierCheck.is(":checked")) { 
     $cashierCheck.fadeIn(); 
     console.log("________________hr") 
    } 
    else { 
     $cashierCheck.fadeOut(); 
     console.log("_______________uncjecked") 
    } 
} 
+1

Bruvoo,增加了一個演示,隨意使用它,對不起,我摸你的帖子喲! ':)'不管怎麼說, 「demo *是用'document .ready'完成的 –

+0

!!謝謝 –

+1

@Tats_innit不錯,我的兄弟來自另一位媽媽。 –

2

用途 「是」 jQuery中的最佳解決方案:

$('.commonCheck').change(function() { 
    if ($(".cashierCheck").is(":checked")) { 
       $('.cashierInput').fadeIn(); 
       console.log("________________hr") 
      } 
      else{ 
       $('.cashierInput').fadeOut(); 
       console.log("_______________uncjecked") 
      } 
}); 

http://jsfiddle.net/PpcLe/