<span>$("div").click(function(){ </span> <span>if ( $(this).hasClass("protected") ) { </span> <span>//do something it does have the protected class! </span> <span>alert("i have the protected class"); </span> <span>} </span><span>});</span>或者
<span>$("div").click(function(){ </span> <span>if ( $('#myDiv').is('.pretty.awesome') ) { </span> <span>//do something it does have the protected class! </span> <span>alert("i have the pretty and awesome classes"); </span> <span>} </span><span>});</span>注意:此方法也使您還可以測試其他事情。即 - 檢查一個元素是否隱藏。
<span>if ( $('#myDiv').is(':hidden') ) { </span> <span>//do something I am hidden! </span> <span>alert("i am hidden!"); </span><span>}</span>
在jQuery中,您可以通過使用HasClass()方法與邏輯運算符結合使用hastClass()方法來檢查元素是否具有多個類。例如,如果您想檢查一個元素是否具有“ class1”和“ class2”,則可以使用以下代碼:
>如果尚不具有jQuery,我可以使用jQuery將類添加到元素中嗎? Here’s how you can do it:
if (!$('#element').hasClass('class1')) {
$('#element').addClass('class1');
如何使用jquery?
>如何從元素中刪除類?以下是一個示例:
$('#element')。 removeClass('class1');
在此代碼中,$('#element')選擇具有id“ element''的元素,然後ememoveClass('class1')將'class1'刪除。元素使用jQuery完全具有任何類。您可以通過檢查attr('class')方法返回未定義來做到這一點。以下是您可以做到的:
在此代碼中,$(#element')在帶有ID'element'的元素中選擇元素,然後選擇“ element'',class('class'')屬於元素的屬性。如果不是不確定的,則該元素至少有一個類。
>
在元素上切換一個類,您可以在jQuery中使用toggleclass()方法來切換元素上的類。這意味著,如果元素具有類,將被刪除;如果沒有課程,它將被添加。以下是一個示例:
$('#element')。 toggleclass('class1');
在此代碼中,$('#element')選擇具有ID'element'的元素,然後toggleclass('class1'
以上是jQuery檢查元素是否已連接的詳細內容。更多資訊請關注PHP中文網其他相關文章!