简体   繁体   中英

AJAX Load div ID's children

Lets say i have this:

$('a').each(function() {
    $(this).click(function(e) {
        e.preventDefault();
        var href = $(this).attr('href');
        $('#somediv').load(href + ' #foo');
    });
});

Now how would I make it load the inner contents of #foo and not the actual div #foo

Still not quite sure what I mean?

<div id="foo">
    <!-- Load these divs only -->
    <div class="children">bar</div>
    <div class="children">bar</div>
    <div class="children">bar</div>
    <div class="children">bar</div>
    <div class="children">bar</div>
    <!-- // -->
</div>

I want to load the inner contents of a div only. Any help is greatly appreciated!

EDIT: SOLVED

I used the unwrap method:

parent.load(href + ' #' + ident + '', function() {
    $('#'+ident+' > div').children().unwrap();
});

You can do this fairly easily if you don't mind using $.get and doing the loading parts by hand, something like this:

$.get(href, function(html) {
    $('#somediv').html(
        $(html).find('#foo').html()
    );
});

This grabs the full chunk of HTML from href using $.get and then, in the success callback, we find the id="foo" element inside the whole pile of HTML, extract its content with .html() and then copy thing into #somediv with the mutator form of .html() .

If you know that #foo will only contain <div> children, then you could try this:

$('#somediv').load(href + ' #foo > div');

I'm not certain that this will work and I don't have a decent test case set up but the .load documentation indicates that it should work. If #foo doesn't contain only <div> s then you'll have to come up with something else to use with the child selector ( > ) . Of course, if #foo contains text that isn't wrapped in an element, then I think you're stuck with the $.get approach above.

You can load only the children of the anchor by using the > selector followed by an asterisk:

$('#somediv').load(href + ' #foo > *');

You can try this:

$(this).click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    $('#somediv').load(href + '#foo *',
    function() {
        $('#somediv #foo').remove();
    });
});

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