search

Home  >  Q&A  >  body text

javascript - jquery each loop gets the width of the div and assigns it to the parent element. Why is the result wrong?

<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? ? ? ?

迷茫迷茫2749 days ago720

reply all(7)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:44:40

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

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:44:40

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

    w += $(this).width();

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:44:40

    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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:44:40

    $("#a1 .aa").each(function(){
        w += $("#a1 .aa").width();
        //这里用错了,应该用$(this).width(),不然累加的是第一个的宽度,
        //用w += $(this).width();我这本地测试530px
    })
    

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:44:40

    $("#a1 .aa").width();//这样默认取的是第一个.aa的宽度,也就是200,所以最后是600
    第二次你删除行内样式后,得到p占据一行的宽度(因为inline-block还没生效),所以得到三倍的整行宽度

    reply
    0
  • 怪我咯

    怪我咯2017-05-19 10:44:40

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:44:40

    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?

    reply
    0
  • Cancelreply