简体   繁体   中英

what's wrong with this jQuery code?

My following code works fine.

$(document).ready(function() {
        $('a.address').click(function() {
            $('#box').slideDown("slow");

            $.ajax({
            type: "POST",
              url: "details.php",
              success: function(html){              
                 $("#msg").html(html);
                } 
            });

        });
    });

However the following does not (only 1 line is changed inside the success:), it loads nothing.. only slidesdown the #box, and #msg inside, however does not load #address.

$(document).ready(function() {
        $('a.address').click(function() {
            $('#box').slideDown("slow"); 

            $.ajax({
            type: "POST",
              url: "details.php",
              success: function(html){
                $("#msg").html($(html).find('#address').html());
                } 
            });

        });
    });

The details.php is:


<div id="info">some text.</div>
    <div id="address">The address</div>

When you write $(html) , you're creating a jQuery object which holds two <div> elements.

Calling .find(...) on this object searches the descendants of the <div> elements.
Since neither element has any child elements, i will never find anything.

Instead, you can call .filter() , which searches the elements in the set (but not their descendants).

Alternatively, you can wrap the returned HTML in a new <div> tag, then call .find() . Since your elements would then be children of the wrapper <div> , they'll be found by .find() .
Unlike .filter() , this will still work if the server is changed to return the <div> you're looking for as a child.

jQuerys .load() help method allows you to load & insert Page Fragments :

$('a.address').click(function() {
    $('#box').slideDown("slow"); 

    $('#msg').load('details.php #address');
});

That is probably what you want to achieve here.

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