gpt4 book ai didi

Javascript/Angular 5 - 单击多个按钮只会影响一个

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:15 26 4
gpt4 key购买 nike

我有一个由 4 个按钮组成的网格,一旦其中一个被单击,它将调用一个名为 doSearch 的函数,该函数检查单击了哪个按钮,并根据它为 last_search 分配一个字符串 值。

但是,当我单击四个按钮中的任何一个时,我似乎总是只按下 edm 按钮并向控制台读取“我是 edm”。

谁能解释一下这是为什么?

html

<!-- grid for music -->
<ng-container *ngIf="show" >
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="edm-btn" type="submit" (click)="doSearch($event)">EDM</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="house-btn" type="submit" (click)="doSearch($event)">House</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="pop-btn" type="submit" (click)="doSearch($event)">Pop</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="dubstep-btn" type="submit" (click)="doSearch($event)">Dubstep</button>
</div>
</div>
</ng-container>

函数代码

doSearch(event): void {

if (document.getElementById('edm-btn')) {
this.last_search = 'edm';
console.log('i am edm');
} else if (document.getElementById('house-btn')) {
this.last_search = 'house';
console.log('i am house');
} else if (document.getElementById('pop-btn')) {
this.last_search = 'pop';
console.log('i am pop');
} else if (document.getElementById('dubstep-btn')) {
this.last_search = 'dubstep';
console.log('i am dubstep');
}
}

修复:

我决定不传递按钮的id,而是直接传递一个字符串到doSearch的函数调用中

html

<!-- grid for music -->
<ng-container *ngIf="show" >
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="edm-btn" type="submit" (click)="doSearch('edm')">EDM</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="house-btn" type="submit" (click)="doSearch('house')">House</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="pop-btn" type="submit" (click)="doSearch('pop')">Pop</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="dubstep-btn" type="submit" (click)="doSearch('dubstep')">Dubstep</button>
</div>
</div>
</ng-container>

函数

doSearch(category): void {

console.log(JSON.stringify(category, null, 2));
if (category === 'edm') {
this.last_search = 'edm';
console.log('i am edm');
} else if (category === 'house') {
this.last_search = 'house';
console.log('i am house');
} else if (category === 'pop') {
this.last_search = 'pop';
console.log('i am pop');
} else if (category === 'dubstep') {
this.last_search = 'dubstep';
console.log('i am dubstep');
}
}

最佳答案

这是因为无论您通过什么事件,您的第一个条件始终为真。您正在传递一个事件,而不是实际数据,并检查一个元素是否存在,即使它已经存在。

关于Javascript/Angular 5 - 单击多个按钮只会影响一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49422459/

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