使用knockout.js,如何在绑定到段落<p>
元素的text属性的文本中包含回车符。
在我的ViewModel中,我生成了一个绑定到View中<p>
的文本字符串。我想在浏览器显示换行符的字符串中包含回车符。
在字符串中包含<br />
或Environment.NewLine
似乎不起作用。
答案 0 :(得分:60)
您需要在元素中设置css属性。 white-space: pre-wrap
<p style="white-space: pre-wrap">First name: <strong data-bind="text: firstName">todo</strong></p>
<p>Last name: <strong>todo</strong></p>
function AppViewModel() {
this.firstName = "Bert" + " \n " + "Test";
this.lastName = "Bertington";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
然后代码有效。与\n
答案 1 :(得分:18)
您可以使用html binding。
JS:
function AppViewModel() {
this.firstName = "Bert<br\>Test";
this.lastName = "Bertington";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
查看:
<p>First name: <strong data-bind="html: firstName">todo</strong></p>
<p>Last name: <strong>todo</strong></p>
答案 2 :(得分:0)
您也可以使用spans来获取绑定,然后html将照常使用。
<span data-bind="text: firstName"></span><br /><span data-bind="text: lastName"></span>