2013-02-15 57 views
-1

我想這樣做的條件:的jQuery - 如何不觸發事件時,對象沒有類

if (this div has NO class firing on) { 

     // do nothing when click on it 

    } // else do something 

這可能嗎?

我傾向於這樣做,因爲它是與另一個學生團隊合作的編碼約束。但是,如果這個問題令人困惑和不清楚,我很抱歉。

回答

3

我不確定我是否正確解釋了您的問題,但我相信您只是想在觸發事件的元素具有某個類時執行某個回調。在這種情況下,你可以做你的回調是這樣的:

$("#someId").on("click", function() { 
    if (!$(this).hasClass("someClass")) 
     return false; 

    // Do your stuff here, if we get here, the element has the desired class 
}); 

有了這個解決方案,您將捕獲的事件,但你會做什麼,早逃回調如果元素不具備類你感興趣

更新:

如果你是不是在找任何特別的班,只是想確保它不具有任何類的話,那麼你可以做這樣的事情,而不是:

$("#someId").on("click", function() { 
    if ($(this).prop("class").length === 0) 
     return false; 

    // Do your stuff here, if we get here, the element has no class 
}); 
+0

完美!非常感謝你的回答,雖然我的問題太固執了。 – 2013-02-15 15:59:11

+0

@AjarnCanz我的榮幸! – 2013-02-15 16:02:06

1

你正在做錯誤的方式。 將類添加到div,您想操縱,然後您可以使用選擇器或hasClass。

1

這是一個問題的一個非常模糊的描述,這是一個非常籠統的回答:

$('div').each(function() { 
    if (!this.hasAttribute('class')) { //has no class 
     $(this).off(); //requires the use of on(), but removes all event handlers 
    } 
    $(this).on('click', ...) 
}); 
2

您可以委派,並檢查是否元素有一個類(不是空單) - 現在它只會觸發如果div有一個類

$('parentelement').on('click','div:not([class=""])[class]',function(){ 

}); 
1

我不明白你的問題。但我想你想要這樣的東西。

if($(this).hasClass('anyClass')){ 
//do nothing 
return false; 
}else{ 
//Do something 
} 

注意:您試圖以錯誤的方式完成它。嘗試找出一些替代方法。