2014-06-28 24 views
2

我需要運行功能複選框從未選中變爲已選中。檢查複選框的轉向時間

因此,我使用.change事件來觸發所有事件,但在運行該函數之前使用.prop進行檢查,以確保該複選框實際上已選中或未選中,對嗎?

<form> 
    <input class="target" type="checkbox" value="Field 1"> 
</form> 

$(".target").change(function(){ 
    if(this.prop("checked", true)){ 
     alert("this is checked"); 
    } else { 
     alert("this is not checked"); 
    } 
}); 

上面的代碼不工作,我不知道爲什麼...

我選擇了.target,它是調用.change事件偵聽器。

.targetthis,因爲它調用了.change方法。

所以函數說「當.target改變時,檢查.target屬性是否爲」checked「,如果是,則爲alert,否則,提醒其他人。

在jQuery的.change文檔中,它表示「更改事件發送到元素時,其更改。」 他們講的是不是.val的元素吧?完全不同的「價值」。因爲.target.val永遠不會改變,因爲它現在是硬編碼的。

回答

1

最簡單的方法是尤斯$(this).is(":checked")來處理,如果不然,如:

$(".target").change(function(){ 
    if($(this).is(":checked")){ 
     alert("this is checked"); 
    } else { 
     alert("this is not checked"); 
    } 
}); 

Becouse你需要檢查,如果檢查,沒有設定值檢查。並且this沒有.prop()您需要使用Jquery Object $(this)

LIVE DEMO

編輯

我一些錯演出]約.is() VS .prop()測試後.prop().is()快得多。

兩者都會給我們相同的結果,但.is()比較慢。

$(".target").change(function(){ 
     if($(this).prop(":checked")){ 
      alert("this is checked"); 
     } else { 
      alert("this is not checked"); 
     } 
    }); 

還是要快得多:

$(".target").change(function(){ 
      if(this.checked){ 
       alert("this is checked"); 
      } else { 
       alert("this is not checked"); 
      } 
     }); 

Test performance .is() vs .prop()

+0

與使用'.is相比,使用'.prop(「checked」=== true) ( 「:勾選」)'?在附註中,'''在這種情況下做了什麼?我知道':'用於特定的jQuery **選擇器**,基本上是一個jQuery擴展ie。由jQuery自己定義的東西。但':checked'不是選擇器,它不會選擇任何內容,那麼冒號是什麼意思? – fuzzybabybunny

+0

我似乎無法找到關於僞選擇器利弊的文檔? http://api.jquery.com/checked-selector/ – fuzzybabybunny

+0

哦,是的,我認爲使用'.prop'需要jQuery來搜索所選DOM **對象**的所有屬性。它需要等待瀏覽器創建DOM對象,然後需要搜索DOM對象的'checked'屬性並返回它是否找到它。聽起來正確嗎? – fuzzybabybunny

1

當前你試圖調用方法prop對一個元素(因爲它不是一個jQuery對象,它不存在)。你需要檢查它的值,而不是設置它。將this.prop("checked", true)更改爲$(this).is(':checked')

1

您正在使用設置器版本prop,也就是說您要將複選框設置爲checked。您應該使用prop的獲取版本。

if($(this).prop('checked') === true){ 
    alert("this is checked"); 
} else { 
    alert("this is not checked"); 
} 

編輯:我的壞,後期這裏,只是確保不正確使用道具。更新了這個參考。

if(this.checked === true) { ... 
+0

這不起作用。可能是因爲'this'使用不正確。 – fuzzybabybunny

+0

這樣做的效果:'if($(this).prop(「checked」=== true))' – fuzzybabybunny

0

試試這個:

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

$(document).ready(function() { 
    $(".target").click(function() { 
    if ($(".target").is(":checked")) { 
     alert("this is checked"); 
     } 
     else{ 
      alert("this is not checked"); 
     } 
    }); 
});