如何使用 JQuery 在 AJAX 回调中查找元素?

发布于 2024-12-29 09:59:39 字数 438 浏览 1 评论 0原文

每当我尝试查找 AJAX 返回页面的正文时,它都会返回 null。这是我的 JQuery 代码:

$(document).ready(function(){
$("#button").click(function(){
    $.ajax({
            url: 'testpagec.php', 
            type: 'GET',

            success: function(data) {
                var test = $(data).find('body');
                alert(test.html());

            }
        });
    return false;
});
});

这在纸面上看起来很完美,但它没有按预期工作。有解决这个问题的想法吗?谢谢。

Whenever I try to find say, the body of the returned page from AJAX, it returns null. Here's my JQuery code:

$(document).ready(function(){
$("#button").click(function(){
    $.ajax({
            url: 'testpagec.php', 
            type: 'GET',

            success: function(data) {
                var test = $(data).find('body');
                alert(test.html());

            }
        });
    return false;
});
});

This looks perfect on paper but it's not working as intended. Any ideas on fixing this? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绅刃 2025-01-05 09:59:39

对我有用的是

 var $data = $('<div>').html( data ); 
 $data.find('body'); // this works now

上面的原因是因为 body 不是祖先,因此 find 不起作用,为数据提供根级元素将确保 find 有效。您还可以使用.filter

$data.filter('body');  

What works for me is this

 var $data = $('<div>').html( data ); 
 $data.find('body'); // this works now

The reason the above works is because body was not an ancestor hence find didn't work, giving the data a root level element will ensure find works. You can also use .filter.

$data.filter('body');  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文