jquery中的attr属性

1.attr属性
首先看一例代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="js/jquery-3.0.0.js"></script>
    <style type="text/css">
        img{
            width: 300px;
            height: 300px;
            border: 5px solid #ccc;
        }
    </style>
</head>
<body>
    <img src="img/1.jpg"/>
    <script type="text/javascript">
        $(function(){
            $("img").click(function(){
                //alert(1);
                $("img").attr("width","500");
                $("img").attr("height","500");
            })
        })
    </script>
</body>
</html>

读者朋友觉得上面的代码中,有问题么?
如果有的话,问题出在哪儿?
那我们试一下,看它有没有获取到img的宽度呢?

$("img").click(function(){
    console.log($("img").attr("width"));
    $("img").attr("width","500");
    $("img").attr("height","500");
})

console.log的结果是undefined
这说明了没有获取到width。

我们看一下内联的写法

<img src="img/meinv.jpg" width="300" height="300"/>
<div style="width:500px;height:300px;background: #f99;">
    记得加px   
</div>

长时间不同内联样式,居然忘却了它的存在。
写成上面第一种这种写法就可以正常获取,原因目前正在探索中。
补充:原因已经找到
因为attr设置的是属性

<div style="width:500px;height:300px;background: #f99;">
    记得加px   
</div>

就像上面这个例子,属性是style,而不是width或者height或者background;
但下面这个就不一样了,

<img src="img/meinv.jpg" width="300" height="300"/>

属性时width和height。
代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="js/jquery-3.0.0.js"></script>
    <style type="text/css">
        img{
            border: 5px solid #ccc;
        }
    </style>
</head>
<body>
    <img src="img/1.jpg" width="300" height="300"/>
    <script type="text/javascript">
        $(function(){
            $("img").click(function(){
                //alert(1);
                console.log($("img").attr("width"));
                $("img").attr("width","500");
                $("img").attr("height","500");
            })
        })
    </script>
</body>
</html>

重点在这里

<img src="img/1.jpg" width="300" height="300"/>

我们再看看这两行代码

$("img").attr("width","500");
$("img").attr("height","500");

还可以这样写:

$("img").attr({"width":"500","height":"500"});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值