Knockout.js按钮仅在observableArray的最大索引上可见

Knockout.js button only visible on maximum index of observableArray

本文关键字:索引 按钮 js observableArray Knockout      更新时间:2023-09-26

我有一个表,我想在最后一行显示一个按钮,但只在最后一行显示。下面的代码用于显示和隐藏按钮,但它显示在每行上。

如何只在最后一行显示呢?

Viewmodel:

var loadCustomFileName = function () {
    for (i = 0; i < self.GetCanSeam().length; i++) {
        var obj = {
            appendFileName: parseFileName(i),
            displayFileName: parseDisplayName(i)
            if (i == self.GetCanSeam().length - 1) {
                self.isMax(true);
            }
        };
        self.GetCustomFile.push(obj);            
    }
};

视图:

<div class="csFormField" data-bind="visible: GetCustomFile().length > 0">
    <table style="width: 100%;">
        <thead>
            <tr>
                <th>File Name Template</th>
                <th>File Name Append</th>
            </tr>
        </thead>
        <tbody data-bind='foreach: GetCustomFile()'>
            <tr>
                <td><p class="cs-label"><label data-bind="text: displayFileName" /></p></td>
                <td><p><input class="cs-input" data-bind="textInput: appendFileName" />
                       <button class="addFormat" data-bind="visible: isMax">+</button></p></td>
            </tr>
        </tbody>
    </table>
</div>

我认为你的isMax是在父上下文上初始化的。不妨试试这个

var obj = {
    appendFileName: parseFileName(i),
    displayFileName: parseDisplayName(i)
};
obj.isMax = ko.observable(i==(self.GetCanSeam().length - 1));
self.GetCustomFile.push(obj);  

您可以比较forloopindex。如果它到达最后一个元素,那么按钮就可见了。
例如:https://jsfiddle.net/kyr6w2x3/12/

 self.ArrayLength = ko.observable()
 self.ArrayLength(self.GetCustomFile().length);

HTML:

<button class="addFormat" data-bind="visible: $index() == $parent.ArrayLength() -1">+</button></p></td>