如何使用三元运算符将表列的colspan属性与值进行数据绑定?
我尝试过这样的事情:
<td data-bind="attr: { colspan: condition() ? 3 : 4 }"> .... <td>
但它始终将colspan设为4(假设条件始终为假)
我的问题是我使用了错误的语法来绑定属性吗?
任何答案将不胜感激...在此先感谢您。
答案 0 :(得分:0)
这似乎有用吗?
function ViewModel() {
var self = this;
self.isValid = ko.observable(true);
self.toggleColspan = function () {
console.log('changed to colspan ' + (self.isValid() ? 4 : 3));
return self.isValid(!self.isValid()); };
};
ko.applyBindings(new ViewModel());
table tr td {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<a href="#" data-bind="click: toggleColspan">toggle</a>
<table>
<thead>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
</thead>
<tbody>
<tr>
<td data-bind="attr: { colspan: $root.isValid() ? 3 : 4 }">body1</td>
</tr>
</tbody>
</table>