jQuery: Why does .width() sometimes return 0 after inserting elements with .html()?

前端 未结 6 1264
误落风尘
误落风尘 2021-02-07 00:57

I am getting some html and inserting it with .html(), after which I am trying to get the width of one of newly inserted elements with .width() (which h

6条回答
  •  感动是毒
    2021-02-07 01:35

    Not sure 100% but I think that your problem is that the code called outside the function where you attach the elements doesn't recognize the newly created elements. A quick example:

    If you can tell us what you're doing exactly we'll surely find a solution.

    LATER EDIT

    Now that you posted code, I can actually help. You need to run this code:

    $('.box', boxOutput).each(function(i) {
        boxWidth += $(this).width(); /* this is where sometimes width returns 0 */
    });
    

    in the function in your ajax response function. Example:

    $.get('script.php', function(data) {
        $('#elem').html(data);
        // your code for width()
    });
    

    Hope this helps.

提交回复
热议问题