下拉框用于过滤HTML中的元素

时间:2014-03-13 19:17:18

标签: javascript html filter

我想使用下拉框在div框中过滤我的文档。我使用脚本给每个元素a或b,并保持隐藏。这个想法是显示从下拉过滤器框中选择的任何元素。

代码:

<script> function toggleElement(id) {
if(document.getElementById(id).style.display == 'none')
{
    document.getElementById(id).style.display = '';
}
else
{
    document.getElementById(id).style.display = 'none';
}
}
</script>

<div style="height:200px;width:895px; max-width:100%; border:1px solid #ccc;font:16px/26px;overflow:auto;">
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>
<div id="b" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">B</a> <br></div>
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>
<div id="b" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">B</a> <br></div>
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>

</div>

<div style="width:895px; max-width:100%; text-align:right;">
<form action="url">
<select name="View:">
<option value="All"><a href="javascript:toggleElement('a', 'b')">All</a></option>
<option value="Tenant"><a href="javascript:toggleElement('a')">A</a></option>
<option value="Landlord"><a href="javascript:toggleElement('b')">B</a></option>
</select>
</form>
</div>

如果更容易可视化,这是一个包含代码的JSFiddle:http://jsfiddle.net/Fn5qw/

1 个答案:

答案 0 :(得分:1)

首先,您不能在多个元素中使用相同的ID,例如使用div标签:

<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>
<div id="b" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">B</a> <br></div>
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>
<div id="b" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">B</a> <br></div>
<div id="a" style="display:none"><a href="/wp-content/uploads/2014/02/Updating-WP-Content.docx">A</a> <br></div>

尝试使用类而不是您可以将多个元素引用到同一个类。我在JSFiddle中对您的代码进行了一些更改,以使其根据您的规范工作。如果这是你正在寻找的,请告诉我。

JSFiddle: http://jsfiddle.net/Fn5qw/2/