Test data:
function Person (name,age) { var-self = this; Self.name = ko.observable (name); Self.age = ko.observable (age); Self.isshow = Ko.observable (""); self.html = "<div> no div</div>", self.isred = True } var person = new Person ("Tom"); Ko.applybindings (person);
One, text binding
For example, the text display of a tag such as Div, span, and text bindings are HTML-encoded.
<div data-bind= "Text:name" ></div> <span data-bind= "Text:18" ></span>
Second, visible binding
If the variable or expression is true, the display is normal; otherwise set: Display:none.
<div style= "color:red;" data-bind= "visible:isshow" > Show or do not show </div> <div style= "color:red;" Data-bind= "Visible:age () >=" > adult or minor </div>
Here is a small suggestion, JS, for the false case has: Boolean type: false, Numeric type: 0, Character type: "", there are null and undifined. Sometimes you see someone write this: if (str! = NULL && str! = "") {...}, you can actually abbreviate: if (str) {...}
Third, HTML binding
Setting the innerHTML property of an element does not HTML encode the bound content, so it can cause HTML attacks. So you need to encode yourself, or use the text binding instead.
<div data-bind= "html:html" ></div>
Iv. attr Binding
Attr can set the basic attributes of an HTML element, such as the SRC attribute of img, the href attribute of a, and so on. The Attr property is an object that can set multiple binding properties.
<a data-bind= "attr:{href: ' Default.aspx?name= ' +name (), Title:name},text:name" ></a>
V. Style binding
The style binding is used to format the DOM element, setting or removing the style based on the true/false of the variable or expression. CSS binding is recommended if the style is more complex.
<div data-bind= "style:{color:isred? ' Red ': ' Yellow '} ' >style bindings </div>
Vi. CSS Bindings
CSS adds class attributes to DOM elements based on the true or false of a variable or an expression.
<div data-bind= "css:{red:isred}" >css bindings </div>
Vii. Summary
As you can see, KO can also be used for style binding in addition to data binding. In short, let's try to minimize the manipulation of the DOM. The related bindings for form fields are not mentioned above and are explained later.
Knockoutjs Learning Note 05: Controlling text and appearance bindings