2017-08-11 66 views
0

我想弄清楚如何將「或」語句添加到腳本。如果.content大於245px,或者div.content在其內部的任何地方都沒有.landing-no-display,那麼請將該類.show添加到.more。如果div有高度或類存在,然後添加類

我在下面的方式無法正常工作...類.show始終得到應用。

if ($('.importantNotice .content').height() >= 245 || ($('.importantNotice .content .landing-no-display'))) { 
    $('.importantNotice .more').addClass("show"); 
} 

回答

0

首先使用變量來使jQuery的更有效(不使用一個選擇兩次)和使用jQuery樹的遍歷方法DOM導航例如find()next()等,而不是使用複雜的CSS選擇器

樹遍歷:https://api.jquery.com/category/traversing/tree-traversal/

選擇器效率:https://learn.jquery.com/performance/optimize-selectors/

你的情況$('.importantNotice .content .landing-no-display')將始終返回true,因爲它返回jQuery對象,這將是在if條件下強制爲true。

您需要使用該對象的.length屬性來確保找不到元素。

var $importantNotice = $('.importantNotice'), 
    $importantNoticeContent = $importantNotice.find('.content'), 
    $importantNoticeMore = $importantNotice.find('.more'); 

if ($importantNoticeContent.height() >= 245 ||$importantNoticeContent.find('.landing-no-display').length) { 
    $importantNoticeMore.addClass("show"); 
} 
+0

謝謝@godblessstrawberry。我認爲.hasClass必須指定要檢查的項目。在我的情況下,我想知道類.landing-no-display是否存在於任何內部,作爲.content的後代而不指定它分配給的項目。 – Brandon

+0

@Brandon得到了它,更新了答案 – godblessstrawberry

0

您需要檢查第二jQuery對象的length財產。目前,由於jQuery對象被強制爲布爾值,它總是等於true。試試這個:

if ($('.importantNotice .content').height() >= 245 || $('.importantNotice .content .landing-no-display').length) { 
    $('.importantNotice .more').addClass("show"); 
} 
相關問題