简体   繁体   English

使用JS / jQuery根据子div的内容使div不可见

[英]Using JS/jQuery to make a div invisible based on the contents of a child div

Context 语境

I have a page that is populated with several <div> s which are filled by parsing a JSON response after the user has submitted a search through a previous form. 我有一个页面,其中填充了几个<div> ,这些页面在用户通过以前的表单提交搜索后通过解析JSON响应来填充。 So far this works fine, and the resulting html roughly looks like: 到目前为止,这工作正常,并且生成的html大致如下所示:

<div class="parent">
    <p>some info</p>
    <img (relevant image)>
    <div class="child">value</div>
</div><!--/parent-->

<div class="parent">
    <p>some info</p>
    <img (relevant image)>
    <div class="child">value1</div>
</div><!--/parent-->

etc

In addition, this page has a select menu, the options for which are also populated by parsing the JSON response, and this select contains every possible (value) that could be found in these divs. 此外,此页面还有一个select菜单,还可以通过解析JSON响应来填充其选项,并且该select包含在这些div中可以找到的所有可能的(value)

<select id="select">
    <option>value</option>
    <option>value1</option>
    <option>value2</option>
         etc...
</select>

It is worth mentioning some divs use the same value , so any given value may appear several times on the page, or might not appear at all, but any div class="child" can only hold 1 value. 值得一提的是,某些div使用相同的value ,因此任何给定的value可能在页面上出现几次,或者根本不会出现,但是任何div class="child"只能容纳1个值。

Goal 目标

What I'm trying to achieve, is a filter of sorts, where the user can select an option in the select menu. 我想要实现的是一种筛选器,用户可以在其中select菜单中的一个选项。 Then, only the parent divs which have a child div that contain that specific value remain visible, the rest has to disappear. 然后,只有具有包含该特定值的child div的parent div保持可见,其余的必须消失。

This is the script I came up with: 这是我想出的脚本:

function filter() {
    var child = document.getElementsByClassName("child"),
        i, len;
    var select = document.getElementById("select");
    var filter = select.options[select.selectedIndex].text;
    for (i = 0, len = child.length; i < len; i++) {
        if (child[i].innerHTML != filter) {
            $(this).closest("div.parent").css("display", "none");
        } else {
            alert("failure")
        }
    })
};

The alert is there solely for testing purposes, so I can see if the script does anything at all. alert仅用于测试目的,因此我可以查看脚本是否执行任何操作。 For now, the script is triggered by a button, but when it's working, I'll tie it to the select menu to make it trigger automatically when the user selects an option. 目前,脚本是由按钮触发的,但是当它起作用时,我会将其绑定到select菜单,以使其在用户选择一个选项时自动触发。

However, this doesn't seem to be working. 但是,这似乎不起作用。 Neither Chrome console nor Firefox dev tools gives an error. Chrome控制台和Firefox开发人员工具均未提供错误。 I simply get the alert, meaning the script deems the contents of var filter to be identical to child.innerhtml . 我只是得到警报,这意味着脚本认为var filter的内容与child.innerhtml相同。 Although this is valid for some instances of var child , it is not valid for all instances. 尽管这对于var child某些实例有效,但并非对所有实例都有效。

I'm not sure why this isn't working. 我不确定为什么这行不通。 I have also tried to replace closest() with parent() , and I have tried to replace css(..) by addClass() but to no avail. 我也曾尝试用parent()替换closest() ,并尝试用addClass()替换css(..) ,但无济于事。

I consider myself a novice on both JS and JQuery, so I might be missing something obvious, but I've looked extensively for answers using Google, SO, MDN, JQuery documentation and every other programming-related website I could think of (even W3schools). 我认为自己是JS和JQuery的新手,所以我可能会遗漏一些明显的东西,但是我一直在广泛使用Google,SO,MDN,JQuery文档以及我能想到的所有其他与编程相关的网站寻找答案(甚至是W3schools )。 After more than 6 hours of searching and trying solutions, I'm at a complete loss. 经过六个多小时的搜索和尝试解决方案,我完全不知所措。 What am I missing here? 我在这里想念什么?

Problem with you implementation is the usage of this , which doesn't refers to element which you want to hide. 实现的问题是this的用法,它并不指向您要隐藏的元素。

You can try 你可以试试

$(child[i]).closest("div.parent").css("display", "none");

instead of 代替

$(this).closest("div.parent").css("display", "none");

You can use .filter() to target the div's to show 您可以使用.filter()定位要显示的div

$("select").on('change', function filter() { 
    //Get selected value
    var selected = $(this).val();

    var parents = $("div.parent");
    //Hide All
    parents.hide();

    //Use filter() to target the divs you want to show
    parents.filter(function(){
        return $(this).find('div.child').text() === selected;
    }).show();
});

I would suggest adding a data attribute to every .child div holding the specific value: 我建议向每个.child特定值的.child div添加一个data属性:

<div class="child" data-value="valueX">valueX</div>

Then, call the following function: 然后,调用以下函数:

function filter() {
    var val = $('#select').val();
    var parents = $('.parent');
    // Hide all parents
    parents.hide();
    // Show paents that contain the specific value
    parents.find('child').filter('[data-value="' + val + '"]').closest('.parent').show();
}

Even better add the data attribute to the .parent element: 甚至最好将data属性添加到.parent元素中:

<div class="parent" data-value="valueX">

And use this function: 并使用此功能:

function filter() {
    var val = $('#select').val();
    var parents = $('.parent');
    // Hide all parents
    parents.hide();
    // Show paents that contain the specific value
    parents.filter('[data-value="' + val + '"]').show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM