2012-12-28 25 views
4

有沒有什麼辦法可以避免在以下聲明中第二次使用$("#check1")如何避免重複創建Jquery包裝?

$("#check1").prop("checked",!$("#check1").prop("checked")); 

通過任何技巧,我可以做下面的事嗎?

$("#check1").prop("checked",!this.prop("checked")); 
+2

怎麼樣'變種C = $( 「#CHECK1」); c.prop(「checked」,!c.prop(「checked」));'? – techfoobar

回答

5

如果你傳遞一個函數作爲回調,你會得到的電流值。

$("#check1").prop("checked", function(i, value) { 
    return !value; 
}); 

.prop(propertyName, function(index, oldPropertyValue))

  • propertyNameThe name of the property to set.
  • function(index, oldPropertyValue) A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.

reference

1
var $check = $("#check1"); 
$check.prop("checked", !$check.prop("checked")); 
3
var el = $("#check1"); 

el.prop("checked",!el.prop("checked")); 
-2

您可以使用此通過這種方式:

$("#check1").prop("checked",!$(this).prop("checked")); 
+0

但是'this'的值取決於上面的運行位置。例如:如果從另一個點擊處理程序中,「this」將引用被單擊的元素而不是複選框。 – techfoobar

+0

@techfoobar抽象地看待陳述,因爲它在問題中被視爲使我的答案錯了? – SaidbakR

+2

類型,因爲您的答案不能直接應用到應用程序,因爲它的前提條件是'this'等於複選框本身,並非總是如此。你的回答是正確的,但只有在綁定到複選框的事件處理程序中觸發時,纔可以。 – techfoobar