2017-02-26 119 views
-2

例如,我有checkbox可以选中或不选中。按HTML列表中的属性显示/隐藏对象

  • 无论何时检查,我希望显示HTML列表中的所有元素。
  • 无论何时未检查,我只想显示一些对象(未过滤),就像其他人不存在一样(我不想要空白等)。

的HTML(把手)名单:

   <ol> 
        {{#each personList}} 
          <li>{{showPerson this}}</li> 
        {{/each}} 
       </ol> 

把手帮手:

 Handlebars.registerHelper('showPerson', function(person) { 
      return person.firstName + " " + person.lastName; 
     }); 

我的过滤功能如下:

function filterOldPeople(person) { 
     return person.age > 60; 
    } 

我想实现的事情是这样的:

var filter; // I am getting this boolean value from checkbox 
if (filter) { 
    doFilter(); // will filter the HTML list that is already rendered 
} 

现在我不知道功能doFilter()应该如何实现这一目标。现在使用jQuery的问题是我能得到的list item的HTML对象,但不是实际的person对象,因此,这将不起作用:

$("li").filter(filterOldPeople).addClass("hide"); 

之类的东西,这正是我需要的。我如何实现这一目标?

+0

你有一个扩展的例子吗?您提供的html代码似乎相当不完整,无法描述整个问题。 – Zim84

+0

嗨,你能发表一个你的列表项的详细例子吗? –

+0

一个更多代码的例子可以帮助我们提供一个解决方案。 – RobertFrenette

回答

0

在这里,你去!只有你想要做的就是把你想要隐藏的所有元素放在一个div中,然后隐藏它,隐藏一个元素比两个元素更容易。

function check() { 
 
    if (document.getElementById("test").checked == true) { 
 
    document.getElementById("two").style.display = "none"; 
 
    } else { 
 
    document.getElementById("two").style.display = "block"; 
 
    } 
 
}
<div class="info"> 
 

 
    <div id="one"> 
 
    If you click on me, #two will hide. 
 
    <input type="radio" id="test" onclick="check()"> 
 
    </div> 
 

 
    <div id="two"> 
 
    Hi, click on the button! 
 
    </div> 
 

 
</div>

+0

我想隐藏的元素与我不想隐藏的元素在同一个div中。这是一个应该由特定属性过滤的列表! – wesleyy

+0

将它们放在一个没有任何风格的div中有多难?无论如何,将相同的类应用于每一个类,并使用Jquery及其.each() –

0

如果你不想使用两个列表,你可以(根据需要添加代码的功能)修改使用类似下面的东西:

HTML

<ul id="theList"> 
    <li class="number">One</li> 
    <li>Red</li> 
    <li class="number">Two</li> 
    <li>Green</li> 
    <li class="number">Three</li> 
    <li>Blue</li> 
</ul> 

<br /><input type="checkbox" id="numbers" checked><label for="numbers">Show Numbers</label> 

JS

$('#numbers').change(function() { 
    $('.number').hide(); 
}); 

https://jsfiddle.net/1ngotz5u/

+0

我无法添加一个类来将应该隐藏的某些元素与应该隐藏的元素分开。我的列表是动态生成的Handlebars模板,而不是静态的。我事先不知道元素,我只需要通过object属性来过滤它们。 – wesleyy

0

我将如何处理这将是:

function filterOldPeople(person) { 
    return person.age > 60; 
} 

// Get all li Elements (useful so we don't have to search the dom multiple times) 

var liElements = $("li"); 

// loop through each li and filter it. 

function filterAges() { 
    liElements.each(function() { 
     if (filterOldPeople($(this).val())) { 
     $(this).addClass("hide"); 
     } 
    }); 
} 

// Show all hidden elements by removing the hide class 

function showAll() { 
    liElements.removeClass("hide"); 
} 

// Create our event 

$("#checkbox").change(function() { 
    if ($(this).is(":checked")) { 
     filterAges(); 
    } else { 
     showAll(); 
    } 
});