data-bind="text: slottext() , attr : {title: Label}"
如果label为null,那么我不想在此显示attr标记include。
答案 0 :(得分:2)
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-
属性,请务必致电{{1关于价值。
这个代码在一个例子中起作用:
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);