We will use the three same methods in the previous chapter to set the content:
Text ()-Sets or returns the textual content of the selected element
HTML ()-Sets or returns the contents of the selected element (including HTML markup)
Val ()-Sets or returns the value of a form field
1. HTML () method
This method is similar to the innerHTML attribute in JS
$ ("#two"). HTML () method gets HTML
$ ("#two"). html ("<span> Hello!</span>")
2, TEXT ()
Similar to the InnerText property in JS
$ ("div"). Text ()//Get the text content of the DIV
$ ("div"). Text ("Hello!"); Sets the text content of the Div.
3, Val ()
Similar to the Value property in JS
$ ("Input[type=text]"). Val ()//Get the value of input
$ ("Input[type=text]"). Val ()//Set the value of input.
Another use of the VLA () method is that it enables Select, checkbox, and radio corresponding options to be selected.
$ (": Radio"). Val ("select number 2nd") set the selected value of the radio box with ID number single as "Select Number 2nd"
$ (": CheckBox"). Val ("Check2,check3") sets multiple options.
The following example shows how to set the content through the text (), HTML (), and the Val () method:
Instance
The code is as follows |
Copy Code |
$ ("#btn1"). Click (function () { $ ("#test1"). Text ("Hello world!"); }); $ ("#btn2"). Click (function () { $ ("#test2"). HTML ("<b>hello world!</b>"); }); $ ("#btn3"). Click (function () { $ ("#test3"). Val ("Dolly Duck"); }); |
The callback function for text (), HTML (), and Val ()
The above three JQuery methods: Text (), HTML (), and Val () also have callback functions. The callback function consists of two parameters: the subscript for the current element in the selected element list, and the original (old) value. Then return the string you want to use with the new value of the function.
The following example shows the text () and HTML () with the callback function:
Instance
code is as follows |
copy code |
$ ("#btn1 "). Click (function () { $ (" #test1 "). Text (function (i,origtext) { return old text: + Origtext + New Text:hello wor Ld! (Index: "+ i +"); }); }); $ ("#btn2"). Click (function () { $ ("#test2"). HTML (function (i,origtext) { Return] old HTML: "+ origtext +" New htm L:hello <b>world!</b> (index: "+ i +") "; }); }); |