質問

I use the parent() and children() methods a lot in JQuery. Typically I do things like this:

<div id="somediv">
    <ul>
        <li id="listitem">item one</li>
        <li id="listitem">item two</li>
        <li id="listitem">item three</li>
        <li id="listitem">item four</li>
    </ul>

    <ol>
        <li id="anotherlist">
            <button id="addItem">additem</button>
        </li>
    </ol>
</div>

$("#addItem").click(function(){
    var num = $(this).parent().parent().parent().children().children("#listitem").size();
    alert(num);
});

The main issue I really want to address is that if the layout of a web page changes then obviously the number of calls made to each of those methods needs to change as well. I don't particularly feel that using them the way I have is necessarily the best way of solving the problem.

Basically when you click the button it just displays the number of items in the first list. (Sorry for not stating earlier).

役に立ちましたか?

解決 2

You can use closest and find. Currently you have four elements with same id i.e. listitem You should use unique ids. You can use common class instead

var num = $(this).closest('#somediv').find("#listitem").size();

Using common class and unique ids.

HTML

<div id="somediv">
    <ul>
        <li id="listitem1" class="someclass">item one</li>
        <li id="listitem2" class="someclass">item two</li>
        <li id="listitem3" class="someclass">item three</li>
        <li id="listitem4" class="someclass">item four</li>
    </ul>

    <ol>
        <li id="anotherlist">
            <button id="addItem">additem</button>
        </li>
    </ol>
</div>

JQuery

var num = $(this).closest('#somediv').find(".someclass").size();

他のヒント

Instead of serieses parent calls, use closest. Instead of serieses of children calls, use find. That way, there are much more significant changes you can make to your HTML structure without impacting your code.

So for instance (note I've changed listitem to a class, see below for why; also, size() was deprecated years ago, use length):

$("#addItem").click(function(){
    var num = $(this).closest("#somediv").find(".listitem").length;
    alert(num);
});

Of course, you don't need closest in that example because #somediv is an ID selector, but if it were a class selector, or something else structural...


As Tushar Gupta points out, your HTML is invalid. You can't use the same id value on multiple elements, id values must be unique. (Hence the word "identifier.")

In your case, you probably wanted to use class.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top