我找不到关于此问题的具体帖子。
基本上,我想要实现的是在 data-product-id
小于 someValue
时隐藏 Compare
文本
经过一番搜索,这就是我想出的。没有错误,但代码不会执行任何操作。我确定我的代码是错误的。
有人可以向我解释我的代码有什么问题吗?如果你们包括/解释正确的方法,那将会很有帮助。
$("a[data-product-id]").filter(function() {
return parseInt($(this).attr("data-product-id")) < 99335;
$('.show').addClass('hide');
});
.hide {
display: none !important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="button" data-product-id="99336" rel="nofollow"><p class="show">Compare</p></a>
<a href="#" class="button" data-product-id="99335" rel="nofollow"><p class="show">Compare</p></a>
<a href="#" class="button" data-product-id="99334" rel="nofollow"><p class="show">Compare</p></a>
<a href="#" class="button" data-product-id="99333" rel="nofollow"><p class="show">Compare</p></a>
最佳答案
存在三个问题:
- 首先,您正在调用
return
,return
语句之后的任何代码都不会执行(意味着$('.show').addClass('hide')
永远不会被调用). - 您实际上根本没有对
data-product-id
值运行条件检查;你只是在返回。将此行包装在if
条件中,而不是使用return
。 - 您的最后一个问题是您只需调用
$('.show').addClass('hide')
。如果 任何 父元素满足条件,这将隐藏所有.show
元素。要更正此问题,您应该使用.find()
与$(this).find('.show')
。
这是一个工作示例:
$("a[data-product-id]").filter(function() {
if (parseInt($(this).attr("data-product-id")) < 99335) {
$(this).find('.show').addClass('hide');
}
});
.hide {
display: none !important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="button" data-product-id="99336" rel="nofollow">
<p class="show">Compare</p>
</a>
<a href="#" class="button" data-product-id="99335" rel="nofollow">
<p class="show">Compare</p>
</a>
<a href="#" class="button" data-product-id="99334" rel="nofollow">
<p class="show">Compare</p>
</a>
<a href="#" class="button" data-product-id="99333" rel="nofollow">
<p class="show">Compare</p>
</a>
关于javascript - 具有过滤值的 jQuery 目标选择器属性并添加新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51924158/