javascript - jquery each loop gets the width of the div and assigns it to the parent element. Why is the result wrong?
迷茫
迷茫 2017-05-19 10:42:40
0
7
751
<script src="jquery.js"></script>
<p id="a1">
    <p class="aa" style="width: 200px;">423423423423423423423</p>
    <p class="aa" style="width: 180px;">42342342342342342</p>
    <p class="aa" style="width: 150px;">123123</p>
</p>
<script>
var w = 0
$("#a1 .aa").each(function(){
    w += $("#a1 .aa").width();//获取宽度。并累加
})
$("#a1").width(w)
</script>
<style>
    .aa{
        display: inline-block;
    }
</style>

Originally the result should be like this

But after removing the inline style, the result is great.

Why remove inline styles. That's it? ? ? ?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(7)
我想大声告诉你

Shorten style标签对放到domjs之前
你的代码结构如果没有行内样式,会先把.aa按照块级元素处理,宽度为100%
js处理完成之后才读取style标签对,把.aa处理为行内块级元素 the width
The synchronized code must be positioned correctly

左手右手慢动作

w += $("#a1 .aa").width();//Get the width. And add up

w += $(this).width();
淡淡烟草味

Put the style in style at the top. The page is loaded from top to bottom. p is a block-level element. .aa{display:inlne-block;} does not work at the bottom

伊谢尔伦
$("#a1 .aa").each(function(){
    w += $("#a1 .aa").width();
    //这里用错了,应该用$(this).width(),不然累加的是第一个的宽度,
    //用w += $(this).width();我这本地测试530px
})
小葫芦
$("#a1 .aa").width();//这样默认取的是第一个.aa的宽度,也就是200,所以最后是600
第二次你删除行内样式后,得到p占据一行的宽度(因为inline-block还没生效),所以得到三倍的整行宽度
刘奇

迷茫

You don’t understand the true meaning of $(selector)
Go and check what will be returned and you will know the problem

$("#a1 .aa").each(function(){
    w += $("#a1 .aa").width(); // 这一句会返回什么?
})

Another question
You need to understand where the style will be added and will it be loaded in advance?
What is the execution of script?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template