Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

javascript - jQuery : Hide select DOM elements created on the fly

In the following code:

$(document).ready( function () {
    var hideInit = function () {
            $(selector1).hide();
    }
    var loadInit = function () {
            //get data
            var thingo = $('<div />');
            //populate thingo with a bunch of divs matching selector1
            $(selector2).append(thingo);
    }
    loadInit();
    hideInit();
});

I am parsing some data and populating the DOM with it in loadInit, and then I wish to .hide each of the elements present in the DOM that was just created which match selector1.

Unfortunately the elements are not being hidden - what have I done wrong here?

Thanks!


Solution

My selectors weren't incorrect, as suggested by many, but it was the order in which I was calling the functions. In order to guarantee that hideInit runs after loadInit has complete, I call it at the end, inside, of loadInit.

$(document).ready( function () {
    var hideInit = function () {
            $(selector1).hide();
    }
    var loadInit = function () {
            //get data
            var thingo = $('<div />');
            //populate thingo with a bunch of divs matching selector1
            $(selector2).append(thingo);
            hideInit();
    }
    loadInit();
});

Thanks for your comments/ answers!


NOT related to : Using jQUery hide() on newly created dom elements

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be achieved with a single line that manipulates the DOM using the append, filter and hide jQuery methods.

  1. $('selector2').append(thingo) - append the items
  2. .filter('selector1') - of the original selector, only select those matching the filter
  3. .hide() - hide the filtered items

Like this:

$(function()
{
    var thingo = $('<div />');
    $('selector2').append(thingo).filter('selector1').hide();
}

Optionally, if you want to hide the appended items, you'll want to add an additional chain after the filter, whereby you could use the find() method, like this:

// this will hide all child divs, so you may want to be more specific
$('selector2').append(thingo).filter('selector1').find('div').hide();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...