首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >怎么切换按钮?

问怎么切换按钮?
EN

Stack Overflow用户
提问于 2016-02-26 10:40:45
回答 1查看 63关注 0票数 0

我试图在按下按钮时按下数组中的数据,并在再次按下按钮时从数组中删除数据(并更改按钮类)。

代码语言:javascript
复制
<button 
    *ngFor="#color of colors"
      [class.selected]="color === selectedColors"
      (click)="onPress(color)">
      {{color.name}}
</button>

我在我的课堂上放了两种方法- onPress & hasColor

代码语言:javascript
复制
onPress(color: Color) {
this.selectedColors = color;
  // ckecking color in array
 if (this.hasColor(this.colorsArray,this.selectedColors.id)) {  
        //need to splice a color from array and change background color to default (to blue color)    
 } else {       
    // if not in colorsArray then push and change class to .selected
   this.colorsArray.push(this.selectedColors.id);
                         }
            } 

 hasColor(arrayC,id) {
      arrayC.forEach(function(item) {
    if (item === id) {
          return true;
        }
          return false;            
      });
    } 

柱塞

我该怎么做呢?hasColor方法返回真或假,但在onPress方法中不返回

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-26 10:48:04

hasColor方法返回true或false

不,不是的。

传递给forEach的匿名函数返回true或false (对于循环中的每个项都是这样做的)。

hasColor函数本身根本没有返回语句。

如果要查看for循环中是否有任何项匹配,则需要使用变量跟踪以查看是否有匹配项,然后在循环结束后返回该变量。

代码语言:javascript
复制
hasColor(arrayC, id) {
    var match = false;
    arrayC.forEach(function(item) {
        if (item === id) {
            match = true;
        }
    });
    return match;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35649519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档