0

Here is my HTML:

<fieldset>
    <legend>Ways I can be contacted</legend>
    <div class="error-message-list"></div>
    <div class="rows">
        <div class="row">
            <div>content</div>
            <div>content</div>                
        </div>
        <div class="row">
            <div>content</div>
            <div>content</div>                
        </div>
    </div>
</fieldset>
<p><a id="count" href="#">Couynt</a></p>

..and here's my Jquery:

    <script type="text/javascript">
        $(document).on({
            click: function(event) { 
                event.preventDefault();
                console.log($(this).parents().siblings('fieldset .rows div.row').length);
            }
        },'#count');
    </script>

When I click on "Count" a zero gets written to the console. I would expect this to be a 2 because there are 2 divs with the class of row within the rows div.

If I just do it on the fieldset, ie, like this:

console.log($(this).parents().siblings('fieldset').length);

Then it returns a 1 as I would expect.

I have also tried

console.log($(this).parents().siblings('fieldset .rows .row').length);

and

console.log($(this).parents().siblings('fieldset > div.rows > div.row').length);

..and many other combinations, but I just can't get it to say '2'!

4

3 回答 3

3

You misunderstand how .siblings work.

.siblings('fieldset .rows div.row')

will select all siblings that match the selector, i.e. elements that are divs with class row and that are descendants of .rows and fieldset elements.

The only sibling of the p element is a fieldset element though, which is certainly not a div.

You can use .find, to select the elements inside the fieldset sibling. For example:

$(this).parent().siblings('fieldset').find('.rows div.row').length

There are many ways to traverse/select the DOM to get the information you want. For example:

$(this).closest('p').prev('fieldset').find('div.row').length
于 2013-06-27T10:10:36.030 回答
1

You can try like this

DEMO --> http://jsfiddle.net/EHYyk/

$(document).on({
            click: function(event) { 
               event.preventDefault();
                console.log($('fieldset .rows .row').length);
            }
        },'#count');

siblings() will give you the adjacent elements, you can directly traverse to the .row class.

于 2013-06-27T10:11:10.143 回答
0

Try less code, http://jsfiddle.net/2PpGN/

var c = $(".rows").children(".row").length;
alert(c)
于 2013-06-27T10:19:40.833 回答