javascript - 具有过滤值的 jQuery 目标选择器属性并添加新类

标签 javascript jquery html css

我找不到关于此问题的具体帖子。

基本上,我想要实现的是在 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/

相关文章:

html - 需要 2 个 100% 宽度的文本框,分为 2 个(50% x 50%)以及一个提交按钮

HTML Viber 链接到特定号码

javascript - 使用 jquery 和 xml 构建虚拟网页

javascript - 是否可以触发/绑定(bind) jQuery UI 事件?

javascript - 使用ajax和css下拉

JQuery简单选项卡程序不显示嵌套的Div标签

html - 让图标完美地出现在中间

javascript 高度数学重新计算每个页面更改

javascript - 一页滚动的网站 - 但如何在动画完成之前禁用滚动

Javascript - <a href></a> 内部警报