我正在尝试弄清楚如何向脚本添加“或”语句。如果 .content 大于 245px 或 div.content 中的任何地方都有 .landing-no-display,则将类 .show 添加到 .more。
我在下面的方法无法正常工作...类 .show 总是被应用。
if ($('.importantNotice .content').height() >= 245 || ($('.importantNotice .content .landing-no-display'))) {
$('.importantNotice .more').addClass("show");
}
最佳答案
首先使用变量使 jQuery 更高效(不要使用一个选择器两次)并使用 jQuery 树遍历方法进行 DOM 导航,例如find()
next()
等而不是使用复杂的 css 选择器
Tree Traversals: https://api.jquery.com/category/traversing/tree-traversal/
Selectors Efficiency: https://learn.jquery.com/performance/optimize-selectors/
在你的情况下 $('.importantNotice .content .landing-no-display')
将始终返回 true,因为它返回将在 if
中强制为 true 的 jQuery 对象条件。
你需要使用.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");
}
关于jquery - 如果 div 具有高度或存在类,则添加该类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639209/