Set Content-text (), HTML (), and Val ()
We will use the three same methods in the previous chapter to set the content:
Text ()-Sets or returns the text content of the selected element
HTML ()-Sets or returns the contents of the selected element (including HTML tags)
Val ()-Sets or returns the value of a form field
The following example shows how to set the content by using the text (), HTML (), and Val () methods:
Instance $ ("#btn1"). Click (function () {
$ ("#test1"). Text ("Hello world!");
});
$ ("#btn2"). Click (function () {
$ ("#test2"). HTML ("<b>hello world!</b>");
});
$ ("#btn3"). Click (function () {
$ ("#test3"). Val ("Dolly Duck");
});
Try it?
The callback function for text (), HTML (), and Val ()
The three jQuery methods above: Text (), HTML (), and Val () also have a callback function. The callback function consists of two parameters: the subscript of 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 a callback function:
Instance $ ("#btn1"). Click (function () {
$ ("#test1"). Text (function (i,origtext) {
Return "Old text:" + origtext + "New Text:hello world!
(Index: "+ i +") ";
});
});
$ ("#btn2"). Click (function () {
$ ("#test2"). HTML (function (I,origtext) {
Return "Old HTML:" + Origtext + "New Html:hello <b>world!</b>
(Index: "+ i +") ";
});
});
Try it?
Setting Properties-attr ()
The JQuery attr () method is also used to set/change property values.
The following example shows how to change the value of the href attribute in the (set) Link:
Instance $ ("button"). Click (function () {
$ ("#w3s"). attr ("href", "//www.w3cschool.cn/jquery");
});
Try it?
The attr () method also allows you to set multiple properties at the same time.
The following example shows how to set the href and title properties at the same time:
Instance $ ("button"). Click (function () {
$ ("#w3s"). attr ({
"href": "//www.w3cschool.cn/jquery",
"title": "JQuery Tutorial"
});
});
Try it?
Tip: Please refer to the site for more information about the JQuery attr () Method!
callback function for attr ()
The JQuery Method attr () also provides a callback function. The callback function consists of two parameters: the subscript of 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 attr () method with a callback function:
Instance $ ("button"). Click (function () {
$("#w3cschool "). attr (" href ", function (I,origvalue) {
return origvalue + "/jquery";
});
});
Try it?
JQuery-setting content and properties