2009-09-28 86 views

回答

276

您可以通過調用jQuery的is功能使用僞選擇:checkbox此功能:

function is_checkbox(selector) { 
    var $result = $(selector); 
    return $result[0] && $result[0].type === 'checkbox'; 
}; 

或者這個jQuery插件:

$.fn.is_checkbox = function() { return this.is(':checkbox'); }; 
+1

這是我一直使用的方法。 – 2009-09-28 18:52:23

+0

你真的不能得到比這更簡單的東西。 – KyleFarris 2009-09-28 20:48:10

+8

爲什麼使用選擇器引擎?這完全沒有必要。 – 2009-09-29 12:14:26

8
$("#myinput").attr('type') == 'checkbox' 
22
>>> a=$("#communitymode")[0] 
<input id="communitymode" type="checkbox" name="communitymode"> 
>>> a.type 
"checkbox" 

或者更多的jQuery的風格:

$('#myinput').is(':checkbox') 
+0

完全有效的。不是最簡單的。 – KyleFarris 2009-09-28 20:48:51

+6

它使用jQuery的選擇器引擎進行保存,在這裏使用它是完全不合適的。第一個變體要好得多,因爲避免了jQuery混淆的'attr()'函數搞亂任何東西的可能性。 – 2009-09-29 09:39:36

+3

@Tim Down是正確的 - 你應該把'attr()'改成'prop()',afaik。 'attr()'並不總是從瀏覽器中獲得「真實」屬性值(即是否檢查)。老實說,不知道爲什麼會出現這種情況,但我後來知道了這一點。 – thekingoftruth 2012-12-10 20:10:49

2

用途:

$("#myinput").attr('type') == 'checkbox' 
6

非jQuery的解決方案是很象一個jQuery的解決方案:

document.querySelector('#myinput').getAttribute('type') === 'checkbox'