如何在数据绑定标签内使用 if 条件来包含 attr 标签
how to use if condition inside data-bind tag to include attr tag
data-bind="text: slottext() , attr : {title: Label}"
如果标签为空,那么我不想显示其中包含的 attr 标签。
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
。
示例中的代码:
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>
data-bind="text: slottext() , attr : {title: Label}"
如果标签为空,那么我不想显示其中包含的 attr 标签。
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
。
示例中的代码:
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>