【发布时间】:2017-06-07 14:43:51
【问题描述】:
data-bind="text: slottext() , attr : {title: Label}"
如果标签为空,那么我不想在其中显示 attr 标记。
【问题讨论】:
标签: asp.net-mvc-4 knockout.js knockout-mvc
data-bind="text: slottext() , attr : {title: Label}"
如果标签为空,那么我不想在其中显示 attr 标记。
【问题讨论】:
标签: asp.net-mvc-4 knockout.js knockout-mvc
Knockout 会为您做到这一点。当您将Label 设置为null 时,它不会盲目地将title: "null" 添加到您的元素中,它实际上会删除该属性。
您可以在源代码中看到这种行为:
// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely // when someProp is a "no value"-like value (strictly null, false, or undefined) // (because the absence of the "checked" attr is how to mark an element as not checked, etc.) var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined); if (toRemove) element.removeAttribute(attrName);
因此,反过来说,如果您想要将null 或false 放入data- 属性中,请务必调用JSON.stringify 的值。 p>
此代码在示例中的作用:
var vm = {
text: "Text",
label: ko.observable("label")
};
ko.applyBindings(vm);
var wrapper = document.querySelector(".wrapper");
console.log("With label:");
console.log(wrapper.innerHTML);
console.log("Without label:");
vm.label(null);
console.log(wrapper.innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="wrapper">
<div data-bind="text: text, attr: { title: label }"></div>
</div>
【讨论】: