jQuery - 设置内容和属性
1. 设置内容- text()、html()以及 val()
三个简单实用的用于DOM操作的jQuery方法:
//设置内容、值
text() - 设置或返回所选元素的文本内容
html() - 设置或返回所选元素的内容(包括 HTML 标记)
val() - 设置或返回表单字段的值
//设置属性
attr()- 设置属性 方法也用于设置/改变属性值
案例:设置文本、表单字段值、属性
<html> <head> <meta charset="UTF-8"> <title>dom 设置属性值</title> <script type="text/javascript" src="../../js/jquery-1.8.3.js" ></script> <script type="text/javascript" src="../../js/jquery-1.8.3.min.js" ></script> </head> <script type="text/javascript"> $(function(){ //文档就绪函数 //设置内容 $("#btn1").click(function(){ $("#test1").text("文本内容1"); }); $("#btn2").click(function(){ $("#test2").html("文本内容2:<font color='red'>设置HTML</font>"); }); }); //设置val function setName(){ $("#name").val("张三"); } //设置属性 function setSx(){ //设置单个属性 $("#url").attr("href","http://www.w3school.com.cn"); //设置多个属性 $("#url").attr({ "href":"http://www.163.com", "title":"网易" }); } </script> <body> <fieldset id="test01"> <legend>1.设置文本-text()</legend> <div style="margin-top: 10px;"> <p id="test1"></p> <p id="test2"></p> </div> <div style="margin-top: 10px;"> <input type="button" id="btn1" value="设置文本"/> <input type="button" id="btn2" value="设置HTML"/> </div> </fieldset> <fieldset id="test02" style="margin-top:10px;"> <legend>2.设置表单字段值-val()</legend> <div style="margin-top: 10px;"> 姓名:<input type="text" id="name" value=""/> </div> <div style="margin-top: 10px;"> <input type="button" id="btn3" value="设置姓名值" οnclick="setName();"/> </div> </fieldset> <fieldset id="test03" style="margin-top:10px;"> <legend>3.设置属性值-attr()</legend> <a id="url" href="www.baidu.com">百度</a><br> <input type="button" id="btn4" value="设置属性值" οnclick="setSx();"/> </fieldset> </body> </html>