
正文
js进阶 11-2 jquery属性如何操作
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
js进阶 11-2 jquery属性如何操作一、总结一句话总结:jquery中的属性用attr方法表示。jquery中都是方法。
1、jquery中的属性的增删改查操作?
一句话总结:jquery中的属性用attr方法表示。jquery中都是方法。
1、jquery中的属性的增删改查操作?
只需要两个方法,
attr():增改查
removeAttr():删
2、jquery中attr()方法和css()方法设置属性的区别?
css方法的更加精确,有单位,如果如果img中没有设置width的话,attr方法弄不到,css方法照样可以
26 alert($('img').attr('width'))
27 //alert($('img').css('width'))
3、jquery如何动态改变元素属性,比如图片不同的高?
使用函数
使用函数来设置属性/值,语法:$(selector).attr(attribute,function(index,oldvalue))
37 $('#btn3').click(function(){
38 $('img').attr('width',function(index,value){
39 return value*(index+1)/3
40 })
41 })
二、jquery属性如何操作1、相关知识
属性操作
- attr() 设置或返回匹配元素的属性和值.
返回被选元素的属性值,语法:$(selector).attr(attribute)
设置被选元素的属性和值,语法:$(selector).attr(attribute,value)
使用函数来设置属性/值,语法:$(selector).attr(attribute,function(index,oldvalue))
- removeAttr() 从元素中移除指定的属性,语法:$(selector).removeAttr(attribute)
2、代码
<!DOCTYPE html>
<html lang="en">
<style>
</style>
<head>
<meta charset="UTF-8">
<title>演示文档</title>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<style>
</style>
</style>
</head>
<body>
<img src="HTML5.png" alt="" width="100">
<img src="HTML5.png" alt="" width="100">
<img src="HTML5.png" alt="" width="100">
<input type="button" id="btn1" value="获取">
<input type="button" id="btn2" value="设置1">
<input type="button" id="btn3" value="设置2">
<input type="button" id="btn4" value="删除"> <script>
$(function(){
//获取元素的属性值
$('#btn1').click(function(){
alert($('img').attr('width'))
//alert($('img').css('width'))
})
$('#btn2').click(function(){
//$('img').attr('width','200')
$('img').attr({
'width':'150',
'height':'300',
'border':'5px'
})
})
$('#btn3').click(function(){
$('img').attr('width',function(index,value){
return value*(index+1)/3
})
})
$('#btn4').click(function(){
$('img').removeAttr('border')
}) })
</script>
</body>
</html>





