jQuery 属性操作
2016-12-28 17:14
316 查看
方法 | 描述 |
---|---|
addClass() | 向匹配元素添加指定的类名 |
attr() | 设置或返回匹配元素的属性和值 |
hasClass() | 检查匹配的元素是否拥有指定的类 |
html() | 设置或返回匹配元素集合中的HTML内容 |
removeAttr() | 从所有匹配的元素中移除指定的属性 |
removeClass() | 从所有匹配的元素中del全部或指定的类 |
toggleClass() | 从匹配的元素中添加或删除一个类 |
val() | 设置或返回匹配元素的值 |
addClass()
这个方法不会替换一个样式类名,它只是简单的添加一个样式类名到元素上。
对所有匹配的元素可以一次添加多个用空格隔开的样式类名
$("p").addClass("myClass yourClass");
通常和.removeClass() 一起使用,用来切换元素:
$('p').removeClass('myClass noClass').addClass('yourClass');
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .newClass{ color: #fff;font-size: 20px; } .newBg{ background: #38b6c5; } </style> <script src="js/jquery.min.js"></script> </head> <body> <p>hello what </p> <p>hello what </p> <p>hello what </p> <script> $(document).ready(function () { $('p').eq(1).addClass('newClass newBg'); }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ font-size: 20px;background: #2b2b2b; } .class1{ background: #ac2925; } .class2{ color: #fff;background: #4cae4c; } </style> <script src="js/jquery.min.js"></script> </head> <body> <h1>Hello P</h1> <div class="class1">what the div</div> <div>find day</div> <div>find day</div> <div>find day</div> <div>find day</div> <p>no no no no</p> <script> $('div').addClass(function (index,currentClass) { var addNewClass; if(currentClass=='class1'){ addNewClass = 'class2'; $('p').text('yes yes yes yes'); } return addNewClass; }) </script> </body> </html>
.attr() .prop()
.attr() .prop() 获取匹配的元素集合中的第一个元素的属性值 或设置每一个匹配元素的一个或多个属性
.attr() .prop() 方法只获取第一个匹配元素的属性值。要想获取每个单独的元素属性值,还需要依靠jQuery的.each()或.map()方法循环
注:.prop() 方法应该用于检索属性值,例如DOM属性(如selectedIndex, tagName, nodeName, nodeType, owenerDocument, defaultChecked, 和defaultSelected),
.attr() 方法检索HTML属性
attributes 和properties 之间的差异在特定情况下是很重要的。jQuery 1.6之前 .attr() 方法在取某些attribute(属性)的值时,会返回property(特性)的值时,会导致结果的不一致。从jQuery 1.6开始, .prop() 方法 返回property的值,而attr() 方法返回attributes的值。
Additional Notes
在Internet Explore 9 之前的版本, 使用.prop() 设置DOM的属性进行赋值时,若所赋值的类型不是基本类型(number, string, 或boolean),而且也没有使用 .removeProp() 方法在DOM元素从文档中被移除前。为了安全在DOM对象进行赋值而不用担心内存泄漏问题,使用.data()方法
注:jQuery禁止改变 <input>或<button>元素的type 特性(attribute),并且所有浏览器下将抛出一个错误。因为Internet explorer不允许改变 <input> 或者 <button>元素的type属性。
相关文章推荐
- jQuery笔记
- jQuery EasyUI 使用笔记
- jquery中使用ajax接收数据并且显示
- 大转盘游戏
- jquery实现图片跟随鼠标
- jQuery对象跟DOM对象相互转换
- jquery post回调函数不执行
- How JQuery Works
- jQuery的each 方法
- jquery导航菜单
- easyui + jquery +ajax + c# 实时看板开发总结
- jQuery实现编辑修改表格table
- [jQuery]html(),text(),val()方法的区别
- Jquery ajax在select中动态加载option并且添加点击事件
- jQuery ajax提交Form表单实例(附demo源码)
- Jquery获取offsetHeight
- jQuery1.9.1针对checkbox的调整
- Jquery 的each事件
- JQuery学习之操作类数组的工具方法_优就业
- jQuery中json对象与json字符串互换