Function: 1. Return the element content, the syntax is "element object.html()"; 2. Set the element content, the syntax is "element object.html(element's new content)"; 3. Use functions to set The content of the element, the syntax is "element object.html(function(index position of the selector, current content of the selector))".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
1. Return element content
When using this method to return a value, it will return the The content of a matching element.
Syntax
$(selector).html()
The example is as follows:
<head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".btn1").click(function(){ alert($("p").html()); }); }); </script> </head> <body> <p>This is a paragraph.</p> <button class="btn1">改变 p 元素的内容</button> </body>
Output result:
After clicking the button:
2. Set element content
When you use this method to set a value, it will overwrite the content of all matching elements.
Syntax
$(selector).html(content)
content Optional. Specifies the new content of the selected element. This parameter can contain HTML tags.
The example is as follows:
<head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".btn1").click(function(){ $("p").html("Hello <b>world!</b>"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button class="btn1">改变 p 元素的内容</button> </body>
Output result:
After clicking the button:
3. Use functions to set the content of elements
Use functions to set the contents of all matching elements.
Syntax
$(selector).html(function(index,oldcontent))
Parameter Description
function(index,oldcontent)
Specifies a function that returns the new content of the selected element.
index - Optional. Receives the index position of the selector.
oldcontent - Optional. Receives the current contents of the selector.
The example is as follows:
<head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").html(function(n){ return "这个 p 元素的 index 是:" + n; }); }); }); </script> </head> <body> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>改变 p 元素的内容</button> </body>
Output result:
After clicking the button:
Recommended related video tutorials: jQuery video tutorial
The above is the detailed content of What functions are implemented by the html method in jquery. For more information, please follow other related articles on the PHP Chinese website!