获得内容 - text()、html() 以及 val()
三个简单实用的用于 DOM 操作的 jQuery 方法:
- text() - 设置或返回所选元素的文本内容
- html() - 设置或返回所选元素的内容(包括 HTML 标记)
- val() - 设置或返回表单字段的值
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"> 8 </script> 9 <script type="text/javascript"> 10 $(document).ready(function() { 11 $("#btn1").click(function() { 12 alert("值为: " + $("#test1").text()); 13 }); 14 $("#btn2").click(function() { 15 alert("值为: " + $("#test1").html()); 16 }); 17 $("#btn3").click(function() { 18 alert("值为: " + $("#test2").val()); 19 }); 20 $("#btn4").click(function() { 21 alert("值为:" + $("#test3").attr("href")); 22 }); 23 24 }); 25 </script> 26 </head> 27 28 <body> 29 <p id="test1">这是一个强调的<em>文字</em></p> 30 <input type="text" id="test2" value="this is a text" /> 31 <a href="//this is a link" id="test3">this is a link</a> 32 <button id="btn1">显示文本</button> 33 <button id="btn2">显示 HTML</button> 34 <button id="btn3">显示值</button> 35 <button id="btn4">显示 href 属性的值</button> 36 </body> 37 38 </html>
设置内容 - text()、html() 以及 val() 设置属性attr()
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"> 6 </script> 7 <script> 8 $(document).ready(function(){ 9 $("#btn1").click(function(){ 10 $("#test1").text("this is paragraph 1"); 11 }); 12 $("#btn2").click(function(){ 13 $("#test2").html("<b>this is paragraph 2</b>"); 14 }); 15 $("#btn3").click(function(){ 16 $("#test3").val("this is text"); 17 }); 18 $("#btn4").click(function(){ 19 $("font").attr("color","aqua"); 20 }); 21 }); 22 </script> 23 </head> 24 25 <body> 26 <p id="test1">这是段落1。</p> 27 <p id="test2">这是段落2。</p> 28 <p>输入框: <input type="text" id="test3" value="这是文本框"></p> 29 <font color="red">Color</font> 30 31 <button id="btn1">设置文本</button> 32 <button id="btn2">设置 HTML</button> 33 <button id="btn3">设置值</button> 34 <button id="btn4"> 修改颜色</button> 35 </body> 36 </html>