Knockout.js carraige return in paragraph text

女生的网名这么多〃 提交于 2019-12-20 11:09:30

问题


Using knockout.js, how do I include a carriage return in the text that is bound to the text attribute of a paragraph <p> element.

In my ViewModel I generated a string of text that is bound to the <p> in the View. I want to include carriage returns in the string which the browser displays with the line breaks.

Including <br /> or Environment.NewLine in the string does not seem to work.


回答1:


You can use the html binding.

JS:

function AppViewModel() {
    this.firstName = "Bert<br\>Test";
    this.lastName = "Bertington";
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

View :

<p>First name: <strong data-bind="html: firstName">todo</strong></p>
<p>Last name: <strong>todo</strong></p>

See fiddle




回答2:


You need to set a css property in your element. 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());

Then the code works. with \n




回答3:


You could also use spans to get your bindings and then the html will be as usual.

<span data-bind="text: firstName"></span><br /><span data-bind="text: lastName"></span>


来源:https://stackoverflow.com/questions/17422895/knockout-js-carraige-return-in-paragraph-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!