03-jquery标签属性的操作
jquery标签属性
jquery的属性操作模块分为四个部分:html属性操作,dom属性操作,类样式操作和值操作
- html属性操作:是对html文档中的属性进行读取,设置和移除操作。比如attr()、removeAttr()
- DOM属性操作:对DOM元素的属性进行读取,设置和移除操作。比如prop()、removeProp()
- 类样式操作:是指对DOM属性className进行添加,移除操作。比如addClass()、removeClass()、toggleClass()
- 值操作:是对DOM属性value进行读取和设置操作。比如html()、text()、val()
html标签属性操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img src=""> <input type="radio" name="sex" checked id="nan">男 <input type="radio" name="sex" id="nv">女 <script src="jquery-3.4.1.js"></script> <script> $(function () { //设置单个属性 // $('img').attr('src','./1.jpeg'); //设置多个属性 $('img').attr({ src:'./1.jpeg', title:'啊' }); //删除标签属性 console.log($('img').removeAttr('title')); //获取标签属性 console.log($('#nan').attr('checked')); //获取对象的属性:prop() 方法设置或返回被选元素的属性和值。当该方法用于返回属性值时,则返回第一个匹配元素的值。当该方法用于设置属性值时,则为匹配元素集合设置一个或多个属性/值对。 console.log($('#nan').prop('checked')); //true console.log($('#nv').prop('checked')) //因为input女里面没有设置checked所以false }) </script> </body> </html>
关于attr()和prop()的区别
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> 男<input type="radio" id='test' name="sex" checked/> 女<input type="radio" id='test2' name="sex" /> <button>提交</button> <script type="text/javascript" src="jquery-3.3.1.js"></script> <script type="text/javascript"> $(function(){ //获取第一个input var el = $('input').first(); //undefined 因为attr是获取的这个对象属性节点的值,很显然此时没有这个属性节点,自然输出undefined console.log(el.attr('style')); // 输出CSSStyleDeclaration对象,对于一个DOM对象,是具有原生的style对象属性的,所以输出了style对象 console.log(el.prop('style')); console.log(document.getElementById('test').style); $('button').click(function(){ alert(el.prop("checked") ? "男":"女"); }) }) </script> </body> </html>
什么时候使用attr(),什么时候使用prop()?
1.是有true,false两个属性使用prop();
2.其他则使用attr();
类的操作
addClass(添加多个类名)
为每个匹配的元素添加指定的类名。
$('div').addClass("box");//追加一个类名到原有的类名
还可以为匹配的元素添加多个类名
$('div').addClass("box box2");//追加多个类名
removeClass
从所有匹配的元素中删除全部或者指定的类。
移除指定的类(一个或多个)
$('div').removeClass('box');
移除全部的类
$('div').removeClass();
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="box"></div>
<script src="jquery-3.4.1.js"></script>
<script>
$(function () {
$('#box').addClass('ac co bd'); //添加多个类名的操作
$('#box').removeClass('co bd'); //删除多个类名
})
</script>
</body>
</html>

浙公网安备 33010602011771号