为什么这个对象在jquery的宽度方法中不起作用?

时间:2017-01-25 14:06:02

标签: javascript jquery html

以下作品:

$(".images").attr("width", ($(this).attr("data-asp") * 50) );
img {
 height: 20px;
  width: auto;
  
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img class="images" data-asp="0.75" src="https://www.gravatar.com/avatar/8a4d2d16b0d988f98779e2737559ef22?s=32&d=identicon&r=PG">
<img class="images" data-asp="1.33" src="https://www.gravatar.com/avatar/8a4d2d16b0d988f98779e2737559ef22?s=32&d=identicon&r=PG">
<img class="images" data-asp="1" src="https://www.gravatar.com/avatar/8a4d2d16b0d988f98779e2737559ef22?s=32&d=identicon&r=PG">

this位于$(".images").attr("width", $(this).height());

但以下this不起作用:

$(".images").width(50 * $(this).attr("data-asp"));
img {
height: 20px;
width: auto;  
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img class="images" data-asp="0.75"  src="https://www.gravatar.com/avatar/8a4d2d16b0d988f98779e2737559ef22?s=32&d=identicon&r=PG">
<img class="images" data-asp="1.33" src="https://www.gravatar.com/avatar/8a4d2d16b0d988f98779e2737559ef22?s=32&d=identicon&r=PG">
<img class="images" data-asp="1" src="https://www.gravatar.com/avatar/8a4d2d16b0d988f98779e2737559ef22?s=32&d=identicon&r=PG">

`this` is in `$(".images").width($(this).height());`

为什么this在jquery的宽度方法中不起作用,而在其他方法中有效?

1 个答案:

答案 0 :(得分:1)

如何尝试读取元素的属性是有缺陷的。您需要遍历集合并单独设置每个集合。

$(".images").each( function () {
    var img = $(this);
    img.width(50 * img.data("asp"));
});