【问题标题】:Hide parent element based on value of child element根据子元素的值隐藏父元素
【发布时间】:2018-03-13 21:44:37
【问题描述】:

我想创建一个过滤函数,它根据 p 标签的值隐藏 div。行为应如下所示:

用户选择一个过滤器,例如>5

  • 循环遍历具有特定类的所有 p-tag
  • 如果 p-tag 中的值与过滤器匹配 (>5),则隐藏每个 p-tag 的值与过滤器值不匹配的所有父 div

我的解决方案如下:

function eraseThis() {

counter = 0
tagList = document.getElementsByClassName("rating")

$(".rating").each(function()
{
if (this.innerHTML < 5) {
     $(this).parent().hide() 
}

counter = counter + 1

    });
}

这给了我正在寻找的结果,但我想知道是否有更优雅/更有效的方法来做到这一点?

标记将类似于:

<div class="movie">
 <p class="rating"> some value </p>
</div>

<div class="movie">
 <p class="rating"> some value </p>
</div>

等等

【问题讨论】:

  • 欢迎来到 Stack Overflow!请查看tour,环顾四周,并通读help center,尤其是How do I ask a good question? 在问题中包含您的HTML 结构示例,最好包含minimal reproducible example 来演示问题,最好是可运行一个使用堆栈片段([&lt;&gt;] 工具栏按钮;here's how to do one)。
  • @AlexYokisama:我怀疑你的意思是.parents(复数)。
  • @T.J.Crowder,也许吧。这取决于标记,我们在这个问题中看不到。对于最亲近的父母,.parent() 就足够了。
  • @AlexYokisama@T.J.Crowder 谢谢大家,更改了代码并添加了一些关于标记的信息

标签: javascript jquery


【解决方案1】:

我认为这应该可以解决问题:

JQuery 代码:

function eraseThis() {
    var tagList = $(".rating");
    tagList.each(function(){

        var $this = $(this);
        if (parseInt( $this.text() ) < 5) {
            $this.parent().hide();
        }

    });
}

HTML代码:

<div class="movie">
 <p class="rating">2</p>
</div>

<div class="movie">
 <p class="rating">9</p>
</div>

这里是完整的代码:JSFiddle

【讨论】:

  • 很好,干得好。刚刚将 parents() 更正为 parent() 。
  • @cubebb : 随时 :-D
  • @cubebb:我刚看到html代码就更正了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多