简体   繁体   English

这个jQuery代码有什么问题?

[英]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. 但是以下没有(在成功内部只改变了1行:),它没有加载任何东西..只滑动#box,而#msg里面,但是不加载#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. 当你编写$(html) ,你正在创建一个包含两个<div>元素的jQuery对象。

Calling .find(...) on this object searches the descendants of the <div> elements. 在此对象上调用.find(...)搜索<div>元素的后代
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). 相反,你可以调用.filter()来搜索集合中的元素(但不是它们的后代)。

Alternatively, you can wrap the returned HTML in a new <div> tag, then call .find() . 或者,您可以将返回的HTML包装在新的<div>标记中,然后调用.find() Since your elements would then be children of the wrapper <div> , they'll be found by .find() . 由于您的元素将成为包装器<div>子元素,因此它们将由.find()找到。
Unlike .filter() , this will still work if the server is changed to return the <div> you're looking for as a child. 不像.filter()这仍将如果服务器更改为返回工作<div>你正在寻找作为一个孩子。

jQuerys .load() help method allows you to load & insert Page Fragments : jQuerys .load .load() 帮助方法允许您加载和插入页面片段

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

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

That is probably what you want to achieve here. 这可能就是你想要在这里实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM