转自:
jQuery笔记三——text/html/val/attr/prop
1.获得内容
三个简单实用的用于 DOM 操作的 jQuery 方法:
- text() - 设置或返回所选元素的文本内容
- html() - 设置或返回所选元素的内容(包括 HTML 标记)
- val() - 设置或返回表单字段的值
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<p>Name: <input type="text" id="test2" value="请输入..."></p>
$("#test").text() ------ This is some bold text in a paragraph.
$("#test").html() ----- This is some <b>bold</b> text in a paragraph.
$("#test2").val() ------ 请输入...(这里是预定义的值)
2.获得属性
jQuery attr() 方法用于获取属性值
<p><a href="http://www.w3cschool.cc" id="w3s">W3Cschool.cc</a></p>
$("#w3s").attr("href") ------ http://www.w3cschool.cc
3.设置内容和属性
还是上面的text、html、val、attr.
attr同时设置多个属性:
$("#w3s").attr({
"href" : "http://www.w3cschool.cc/jquery",
"title" : "W3Schools jQuery Tutorial"
});
4.attr和prop的区别
相比attr,prop是1.6.1才新出来的,两者从中文意思理解,都是获取/设置属性的方法(attributes和properties)。只是,window或document中使用.attr()方法在jQuery1.6之前不能正常运行,因为window和document中不能有attributes。prop应运而生了。