以下作品:
$(".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的宽度方法中不起作用,而在其他方法中有效?
答案 0 :(得分:1)
如何尝试读取元素的属性是有缺陷的。您需要遍历集合并单独设置每个集合。
$(".images").each( function () {
var img = $(this);
img.width(50 * img.data("asp"));
});