在js中创建搜索器



我需要在javascript中创建一个搜索器。我有20张不同id的旗帜图片。我的想法是有一个输入,其中用户键入国家的名称(这将是img标签中的id),它将显示img.

假设你得到了输入的搜索值:

var value = document.getElementById('textbox_id').value

现在你可以插入它的位置:

var imageBox = document.getElementById("app");
var str = `<img alt="${value}" id=`${value}`>`
imageBox.insertAdjacentHTML( 'beforeend', str );

希望我对你有所帮助。

在Angular中,你可以使用RxJS创建一个图像搜索器。请查看我在下面添加的示例代码,以便您对如何完成它有一个概述。

app.component.html

<input #search placeholder="Search" name="seacher" />
<div *ngIf="searchedImage">
<img [src]="searchedImage" />
</div>

app.component.ts

import { AfterViewInit, Component, ElementRef, ViewChild } from "@angular/core";
import { fromEvent } from "rxjs";
import { debounceTime, distinctUntilChanged, tap } from "rxjs/operators";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
@ViewChild("search", { static: false }) search: ElementRef;
imageList = [
{ name: "Image 1", image: "https://picsum.photos/id/237/200/300" },
{ name: "Image 2", image: "https://picsum.photos/id/238/200/300" },
{ name: "Image 3", image: "https://picsum.photos/id/239/200/300" },
{ name: "Image 4", image: "https://picsum.photos/id/236/200/300" }
];
searchQuery: string = "";
searchedImage: string;
ngAfterViewInit() {
fromEvent(this.search.nativeElement, "keyup")
.pipe(
debounceTime(500),
distinctUntilChanged(),
tap((event: KeyboardEvent) => {
this.searchedImage = this.imageList.find(
(item) => item.name === this.search.nativeElement.value
)?.image;
})
)
.subscribe();
}
}

最新更新