开发者

jQuery get width of a clicked element store in variable

I have some basic markup:

<div id="container">
    <div class=".content"></div>
    <div class=".content"></div>
    <div class=".content"></div>
    <div class=".content"></div>
</div>

I would like to get the width of .content each time it 开发者_高级运维is clicked and store it in an array. I have the following jQuery code:

var listWidth = [];
    $('.content').click(function(){
        listWidth.push($(this).width());
    });

    console.log(listWidth);

This is not passing the width value to the array. It does work when I use alert like this:

var listWidth = [];
    $('.content').click(function(){
        alert($(this).width());
    });

    console.log(listWidth);

Can anyone help me out? Many thanks in advance.


Call console.log from within the click event.

var listWidth = [];
$('.content').click(function(){
    listWidth.push($(this).width());
    console.log(listWidth);
});

You are logging the array when it's empty, before the click event pushes anything into the array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜