本教程操作环境:windows7系统、jquery1.12.4版本、dell g3电脑。
jquery 属性操作方法
方法描述
addclass() 向匹配的元素添加指定的类名(class属性值)。
attr() 设置或返回匹配元素的属性和值。
prop() 设置或返回匹配元素的属性和值。
hasclass() 检查匹配的元素是否拥有指定的类(class)。
removeattr() 从所有匹配的元素中移除指定的属性。
removeclass() 从所有匹配的元素中删除全部或者指定的类(class)。
toggleclass() 从匹配的元素中添加或删除一个类(class)。
jquery attr()和prop()方法返回或设置属性
prop() 方法和 attr() 方法相似,都是用来获取或设置元素的 html 属性的,不过两者也有着本质上的区别。
jquery 官方建议:具有 true 和 false 这两种取值的属性,如 checked、selected 和 disabled 等,建议使用 prop() 方法来操作,而其他的属性都建议使用 attr() 方法来操作。
<!doctype html><html><head> <meta charset="utf-8" /> <title></title> <script src="js/jquery-1.12.4.min.js"></script> <script> $(function () { $('input[type="radio"]').change(function(){ var bool = $(this).attr("checked"); if(bool){ $("p").text("你选择的是:" + $(this).val()); } }) }) </script></head><body> <div> <label><input type="radio" name="fruit" value="苹果" />苹果</label> <label><input type="radio" name="fruit" value="香蕉" />香蕉</label> <label><input type="radio" name="fruit" value="西瓜" />西瓜</label> </div> <p></p></body></html>
在这个例子中,我们其实是想通过$(this).attr("checked")判断单选框是否被选中,如果被选中,就获取该单选框的 value 值。可是运行代码后发现:完全没有效果!这是为什么呢?
实际上,对于表单元素的 checked、selected、disabled 这些属性,我们使用 attr() 方法是没法获取的,而必须使用 prop() 方法来获取。因此,我们把 attr() 方法替换成 prop() 方法就有效果了。
其实,prop()方法的出现就是为了弥补 attr() 方法在表单属性操作中的不足。记住一句话:如果某个属性没法使用 attr() 方法来获取或设置,改换 prop() 方法就可以实现。
removeattr()方法删除属性
在 jquery 中,我们可以使用 removeattr() 方法来删除元素的某个属性。
语法:
$().removeattr("属性名")
jquery 类名操作
类名操作,指的是为元素添加一个 class 或删除一个 class,从而整体控制元素的样式。
在 jquery 中,css 类名操作共有以下 3 种。
添加 class。
删除 class。
切换 class。
addclass()方法添加class
在 jquery 中,我们可以使用 addclass() 方法为元素添加一个 class。
语法:
$().addclass("类名")
removeclass()方法删除class
在 jquery 中,我们可以使用 removeclass() 方法来为元素删除一个 class。
语法:
$().removeclass("类名")
toggleclass()方法切换class
在 jquery 中,我们可以使用 toggleclass() 方法为元素切换类名。toggle,其实就是“切换”的意思,之后我们会大量接触这个单词,例如 toggle()、slidetoggle() 等,小伙伴要留意和对比一下。
语法:
$().toggleclass("类名")
toggleclass() 方法用于检查元素是否有某个 class。如果 class 不存在,则为元素添加该 class;如果 class 已经存在,则为元素删除该 class。
【推荐学习:jquery视频教程、web前端】
以上就是jquery操作元素属性的方法是什么的详细内容。