【问题标题】:Data bind in knockout is not working for multiple attributes淘汰赛中的数据绑定不适用于多个属性
【发布时间】:2019-03-19 14:13:27
【问题描述】:

我有一个带有数据绑定的以下 div 标签

它给出以下错误

绑定值: visible:showBannerMessage , style:{backgroundColor: #ffeea8;height: 40px} 消息:无效或意外的令牌

我在哪里犯了错误? 谢谢

【问题讨论】:

  • 我的 div 行如下
  • 报错如下 Bindings value: visible:showBannerMessage , style:{backgroundColor: #ffeea8;height: 40px} Message: Invalid or unexpected token
  • #ffeea8height 之间的 ; 应该是 ,
  • 否。它没有解决问题。
  • 我认为您的意思是:“是的,但不幸的是,这不是唯一的问题”

标签: knockout.js knockout-validation knockout-3.0


【解决方案1】:

您传递给style 绑定的值应该是有效的javascript 对象,而不是css 字符串。你犯了两个错误:

  • property: value 对应由 , 分隔,而不是 ;
  • 字符串值应该用引号括起来。 40px#ffeea8 都应该包含在 '' 中。

即正确的绑定是:

/*              comma -------------v                */
style: { backgroundColor: '#ffeea8', height: '40px'  }
/*            quotes -----^-------^----------^----^ */

这是您的错误视图的复制,显示了您描述的错误,以及包含对这两个更改的修复的正确视图:

// Wrong view
try {
  ko.applyBindings({
    showBannerMessage: true
  }, document.getElementById("wrong"));
} catch(err) {
  console.log("error:", err.message);
}

// Right view:
ko.applyBindings({
  showBannerMessage: true
}, document.getElementById("right"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<!-- with errors -->
<div id="wrong" data-bind="visible:showBannerMessage, style:{backgroundColor: #ffeea8; height: 40px}">Hello world</div>

<!-- without errors -->
<div id="right" data-bind="visible:showBannerMessage, style:{ backgroundColor: '#ffeea8', height: '40px' }">Hello world</div>

【讨论】:

  • 完美!谢谢
猜你喜欢
相关资源
最近更新 更多
热门标签