简体   繁体   中英

Count divs with a certain class

Seems pretty simple but I can't get it to work.

I have two divs with the class 'user'. I want to output "you have 2 divs".

<script type="text/javascript">
    $(document).ready(function() {
        function divcount() {
            var mycount =  $('.user').length(); 
            document.write(mycount)
        }
    });
</script>

I'm sure I'm missing something simple..

它是$('.user').lengthArray的 length属性 )或$('.user').size()jQuery的 size方法 )。

Length is a property not a function. Size is a function.

It's just $('.user').length . It's a property, not a method call.

$(".user").length  // use the length property

$(".user").size()  // use the size method

notice that the code must be include in the $(function(){...}) block; like:

$(function(){
    alert( $(".user").length );
    alert( $(".user").size() );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM