jquery常用获取属性的方法有哪些
时间:2022-03-23 17:24
jquery常用获取属性的方法有:1、attr()方法,可获取并返回指定属性的值,语法“$(selector).attr("属性名")”;2、prop()方法,可返回被选元素的属性值,语法“$(selector).prop("属性名")”。 本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。 jquery常用获取属性的方法有两个: attr()方法 prop()方法 jquery attr()方法 attr() 方法设置或返回被选元素的属性值。 示例:获取img元素 width属性的值 jquery prop()方法 prop() 方法设置或返回被选元素的属性和值。 当该方法用于返回属性值时,则返回第一个匹配元素的值。 示例: attr()和prop()方法的区别 prop() 方法和 attr() 方法相似,都是用来获取或设置元素的 HTML 属性的,不过两者也有着本质上的区别。 jQuery 官方建议:具有 true 和 false 这两种取值的属性,如 checked、selected 和 disabled 等,建议使用 prop() 方法来操作,而其他的属性都建议使用 attr() 方法来操作。 【推荐学习:jQuery视频教程、web前端开发】 以上就是jquery常用获取属性的方法有哪些的详细内容,更多请关注gxlsystem.com其它相关文章!<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
alert("图片宽度为 " + $("img").attr("width"));
});
});
</script>
</head>
<body>
<img src="img/1.jpg" width="200" />
<br />
<button>返回图像的宽度</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
alert("图片宽度为 " + $("img").prop("width"));
});
});
</script>
</head>
<body>
<img src="img/1.jpg" width="200" />
<br />
<button>返回图像的宽度</button>
</body>
</html>