【发布时间】:2019-07-09 22:44:57
【问题描述】:
我正在尝试使用下拉按钮进行 “过滤” 选择。
每当用户单击特定类型的项目(如我的示例中的衣服)时,html 将仅显示符合条件的项目(仅衣服)。我可以设法选择我想要的项目并将其放入一个数组中,但是,当我尝试用新数组替换 div 时,输出为 [object HTML Element]。
有趣的是,如果我console.log 具有特定值的数组,(array[0]) 它显示了我需要的 html 代码。
<div class="dropdown-menu" >
<a class="dropdown-item" onClick="filter('clothes')" >Clothes</a>
<a class="dropdown-item" onClick="filter('electronics')" >Electronics</a>
</div>
<div id="testSearch">
<section name="product">
<img value="clothes" src="./some.jpg" alt="Clothes 01">
<h5>Electronic</h5>
</section>
<section name="product">
<img value="electronics" src="./some2.jpg" alt="Electronics 01">
<h5>Electronic</h5>
</section>
</div>
<!-- My code has different sections with a variety of value/h5 -->
<script>
function filter(x) {
var arraySearch = [];
var input = document.getElementsByName('product');
for (i=0; i < input.length; i++) {
if(input[i].innerHTML.indexOf(x) > 0 ) {
arraySearch[i]= input[i];
result = result + arraySearch[i];
}
}
document.getElementById('testSearch').innerHTML = result;
<!-- my html display only [object HTMLElement], if more than a section matches, then it displays the [object HTMLElement] times the number of sections matched -->
}
</script>
我希望 [object HTMLElement] 的输出是符合条件的部分。
【问题讨论】:
-
首先尝试将
result定义为一个let。let result = result + arraySearch[i]; -
嘿,我有点忘了在 Stack 中输入我的代码,但我在循环之前声明了
var result = " " ;。即使我将代码更改为您推荐的代码,它仍然具有相同的输出。
标签: javascript innerhtml