簡體   English   中英

如何使用JQuery在另一個div中找到div的寬度

[英]How to find width of div inside another div using JQuery

嗨,我正在嘗試運行此代碼,找到div的寬度,這是在另一個div內。 但它運行不正常。 這個怎么做?

我想要div mitem1的寬度

碼:

<!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>
$('.menubar .mitem1').each(function() {
  alert($(this).width());
});

這是一個小提琴

如果要獲取寬度,包括paddingborder (和margin ,可選),請使用outerWidth()

問題1

你忘了在頁面中添加jQuery了。 添加它:

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

問題2

您必須將代碼放入文檔中:

$(function () {
});

問題3

現在你可以遍歷你的項目,並且為了訪問元素的寬度,在jQuery中使用.width()方法:

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

        // now do anything you want with width
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM