【问题标题】:how to use if condition inside data-bind tag to include attr tag如何在 data-bind 标签内使用 if 条件来包含 attr 标签
【发布时间】:2017-06-07 14:43:51
【问题描述】:

data-bind="text: slottext() , attr : {title: Label}"

如果标签为空,那么我不想在其中显示 attr 标记。

【问题讨论】:

    标签: asp.net-mvc-4 knockout.js knockout-mvc


    【解决方案1】:

    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);
    

    source

    因此,反过来说,如果您想要nullfalse 放入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>

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多