码迷,mamicode.com
首页 > Web开发 > 详细

jQuery笔记三——text/html/val/attr/prop

时间:2015-03-20 18:15:50      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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="Mickey Mouse"></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() ------ Mickey Mouse

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应运而生了。

参考:http://www.javascript100.com/?p=877

在遇到要获取或设置checked,selected,readonly和disabled等属性时,用prop方法显然更好

attr方法里面,最关键的两行代码,elem.setAttribute( name, value + “” )和ret = elem.getAttribute( name ),很明显的看出来,使用的DOM的API setAttribute和getAttribute方法操作的属性元素节点
而prop方法里面,最关键的两行代码,return ( elem[ name ] = value )和return elem[ name ],你可以理解成这样document.getElementById(el)[name] = value,这是转化成JS对象的一个属性。

jQuery笔记三——text/html/val/attr/prop

标签:

原文地址:http://www.cnblogs.com/icyJ/p/4353955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!