开发者

Using jquery to hide dynamically added divs

The jquery code below will hide divs ending with -value-wrapper when the page loads. My issue is, that the "Add more values" button will append another row (with the number incremented). When it does, all the divs are revealed. Is there a way to keep the original ones hidden and hide those in 开发者_如何学编程the new set as well?

The html markup looks like this:

<div id="group-information-items">
    <fieldset>
        <legend>Member Information</legend>
        <label>Form label 1</label>
        <table>
            <tr>
                <td>
                <div class="form-radios">
                    <input type="radio" class="form-radio" checked="checked" value="0" name="gci[0][fa][value]" id="edit-gci-value-0"> A
                    <input type="radio" class="form-radio" value="1" name="gci[0][fa][value]" id="edit-gci-value-0">B 
                </div>

                <!-- This is the div that is hidden -->
                <div id="edit-gci-0-fa-list-value-wrapper" class="form-item">
                    <label>List: </label>
                    <textarea name="gci[0][fa_list][value]" rows="5" cols="60"></textarea>
                </div>

                </td>
            </tr>
        </table>

        <!-- WHEN THIS BUTTON IS CLICKED, A CLONE OF THE ROW ABOVE IS APPENDED TO THE TABLE -->
        <!-- THE ONLY DIFFERENCE IS [0] BECOMES [1] AND SO ON -->
        <div class="content-add-more clear-block">
            <input type="submit" value="Add more values" id="edit-gci-add-more" name="gci_add_more">
        </div>
    </fieldset>
</div>

The code that does the initial hide is below:

$("#group-information-items div").each(function() {
        $("div[id$='-value-wrapper']").each(function() {
                        $(this).hide();
        });
});


First, unless I'm missing something, you can greatly simplify that hiding code:

$("#group-information-items").find("div[id$='-value-wrapper']").hide();

This begs the question, though. Why not set a regular static style so the default condition for any of these divs is hidden? As a practice it makes sense to align the default styles with the default logical state of your page elements. So:

div#group-information-items div.form-item { display: none; }

Now all the "new" divs will be hidden. Change your code to show() divs as needed (You haven't shown enough to know how, where, and when you'd do this). If you're looking to attach behaviors to elements created after the initial page load, you should take a look at live() or delegate().


try hiding the divs on the click of the input button:

  $("#edit-gci-add-more").click(function() {
             $("div[id$='-value-wrapper']").hide();
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜