【问题标题】:Knockout JS, How to change Style attributes when changing a value inside an observable arrayKnockout JS,如何在更改可观察数组中的值时更改样式属性
【发布时间】:2020-05-04 07:04:19
【问题描述】:

哟,我正在尝试构建这个小游戏,其中包含 6 个子数组(每个包含 7 个值)的数组生成一个国际象棋场。

当您单击其中一个字段时,它应该将颜色从白色变为红色或从白色变为黄色。颜色属性取决于写入数据数组中的值(与嵌套 div 标记内的 css 绑定一起使用)。

数组“数据”(像矩阵一样构建)如下所示: [ [0,0,1,2,0,2,1], [0,0,0,0,2,2,1]等]

在 HTML 中,我使用“forEach”循环将数组的值绑定到 div 标记并生成国际象棋字段 - 总共 42 个字段 (6*7=42)。

<body>

    <div class="playground">
        <div class="score">
            <div id="p1" style="flex: 2;"></div>
            <div class="void" style="flex: 3;"></div>
            <div id="p2" style="flex:2"></div>
        </div>

        <div class="container1" data-bind="foreach: data.matrix"> 

            <div class="container2" data-bind="foreach: $data"> 
                <div class="blocks">

                    <div data-bind="css: {corny: $data >= '0', white: $data === '0', yellow1: $data === '1', red2: $data === '2'},
                            attr: { 'id': $parentContext.$index() + '_' + $index()},
                            click: $root.chipInserted">
          </div>
        </div>
      </div>
     </div>
    </div>

    </body>


</html>

现在我得到了国际象棋字段,当我在启动脚本之前更改“数据”中的值时,颜色会相应设置。当我点击一个字段时,数组值也会改变,但 div 标签颜色不会。 我该怎么做?

【问题讨论】:

    标签: javascript html css foreach knockout.js


    【解决方案1】:

    好的,我知道了。

    我使用一个包含 42 个数字的字符串作为基础来创建我的矩阵。单击该字段时,矩阵内的值发生了变化。虽然我还必须将矩阵改回一个简单的字符串,并使用我最初创建国际象棋领域的“创建者函数”重用它。

    长话短说:

    let result = self.addColor(id, self.data); 
    //'result' is the new matrix with the changed value
    
    let resultString = self.matrixToString(result()); 
    //'resultString' is the conjoined array - a simple string made from 'result-matrix' 
    //with a length of 42
    
    let newMatrix = self.Spielfeld.creator(resultString);  
    //now put that String into the "matrix-creator function" in order to create the
    //updated matrix
    
    self.data(newMatrix); 
    //put the new matrix into the observable and your viewmodel should update
    

    如果有人对淘汰赛有足够的了解,他们能解释一下为什么必须这样做吗? 我阅读了有关睡眠函数的信息,这些函数无法访问可观察对象,因为访问不会“直接”发生。跟这个有关系吗?

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 2015-07-13
      • 2014-01-22
      • 1970-01-01
      • 2014-01-28
      • 2014-11-02
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      相关资源
      最近更新 更多