3

Hi I am trying to run this code that finds the width of div which is inside another div. but it is not running properly. How to do this?

i want the width of div mitem1

Code:

<!DOCTYPE html>
<html>
    <head>
    <style type="text/css">
        div#mydiv {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
    <script language="JavaScript">
        $('.menubar').each(function(menu){
            var len = $(this).find('.mitem').text().length;
            alert(len);
        });
    </script>
    </head>
    <body>

        <div class="menubar">

            <table border="1"><tr>
                <td><div class="mitem1">Home</div></td>
                <td><div class="mitem1">Communities<ul><li>item1</li><li>item2</li><li>item3</li><li>item4</li><li>item5</li></div></td>
                <td><div class="mitem1">Project Gallery</div></td>
                <td><div class="mitem1">For Our Customer</div></td>
                <td><div class="mitem1">Our Services</div></td>
            </tr></table>

        </div>

    </body>
    </html>
4

2 回答 2

8
$('.menubar .mitem1').each(function() {
  alert($(this).width());
});

这是一个小提琴

如果要获取宽度,包括paddingand border(and margin,可选),请使用outerWidth()

于 2013-05-16T08:50:08.550 回答
3

问题 1

您忘记在页面中添加 jQuery。添加它:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

问题 2

您必须将代码放入准备好的文档中:

$(function () {
});

问题 3

现在您可以遍历您的项目,并访问元素的宽度,使用.width()jQuery 中的方法:

$(function () {
    $('.menubar .mitem1').each(function() {
        var width = $(this).width();

        // now do anything you want with width
    });
});
于 2013-05-16T09:12:34.547 回答