gpt4 book ai didi

javascript - 搜索无法以 Angular 工作的可折叠内容

转载 作者:行者123 更新时间:2023-11-27 23:47:33 24 4
gpt4 key购买 nike

我在我的 Angular 应用程序中实现了可折叠。但是那些可折叠的内容来自数据库服务,我正在 ngFor as- 的帮助下设置这些可折叠的内容

 <input type="text" name="search" class="form-control" id="myInput" onkeyup="myFAQsSearchFun()" placeholder="Enter your query " >


<div *ngFor="let item of faqs;let i = index;" id="div2">
<button class="accordion" (click)="toggleAccordian($event, i)">
<a style="text-decoration:none;" > {{item.question}}</a>
</button>

<div class="panel" hide="!item.isActive">
<p><br> {{item.answer}} </p>
</div>
<br>
</div>

Collapsible 工作正常,但问题是我想根据我在搜索栏中输入的内容来搜索这些内容。为此,我实现了以下代码-

  function myFAQsSearchFun() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("div2");
li = ul.getElementsByTagName("button");
window.alert(li.length);
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}

Window.alert 的输出为“1”。但是 ngFor 循环了 3 次,因为我可以看到 3 个可折叠对象。

我做错了什么。请帮忙。

提前致谢!

最佳答案

  • 不使用 document.getElementById("myInput"),而是使用 Angular 表单获取输入。
  • 您将在 Controller 中获得以 HTML 格式显示的数据,因此无需循环遍历 DOM,您只需在 Controller 本身中过滤数组即可。
  • 过滤后,只需为 FAQ 中的每个元素添加一个标志即可隐藏或显示它们。
  • 根据上述标志在 HTML 中添加 ngIF。

HTML:

<input [(ngModel)]="model.search" >
<div *ngFor="let item of faqs;let i = index;" >
<div *ngIf="!item.hidden">
<button class="accordion" (click)="toggleAccordian($event, i)">
<a style="text-decoration:none;" > {{item.question}}</a>
</button>

<div class="panel" hide="!item.isActive">
<p><br> {{item.answer}} </p>
</div>
<br>
</div>
</div>

JS:

       model = {search: ''};
faqs = [{question:'asf',answer:'asd'}, {question:'asf',answer:'asd'}]
myFAQsSearchFun() {
var input, filter, ul, li, a, i, txtValue;
input = model.search;
filter = input.toUpperCase();
faqs.forEach((faq) => {
if (faq.question.toUpperCase().indexOf(filter) > -1) {
faq.hidden = false;
} else {
faq.hidden = true;
}
});
}

关于javascript - 搜索无法以 Angular 工作的可折叠内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56699686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com