jQuery的.find()上()调用返回&QUOT来自阿贾克斯的数据; [对象的对象] QUOT;而不是DIV [英] jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

查看:161
本文介绍了jQuery的.find()上()调用返回&QUOT来自阿贾克斯的数据; [对象的对象] QUOT;而不是DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找到与 ID =结果在返回的数据 DIV 元素阿贾克斯()使用 .find()。不幸的是,警报(结果)不返回 DIV#结果

下面是我的code:

  $。阿贾克斯({
    网址:网址,
    缓存:假的,
    成功:函数(响应){
        结果= $(响应).find(#结果);
        警报(响应); //工作正常(返回所有HTML)
        警报(结果); //返回[对象的对象]
    }
});
 

解决方案

要具体回答你的问题,它似乎是正常工作。你说,它返回 [对象的对象] ,这是jQuery将与找到(#结果)方法。它返回匹配 jQuery的元素找到查询。

尝试获得该对象的属性,如 result.attr(ID) - 它应该返回结果


在一般情况下,这个答案取决于是否不 #result 是最高级别的元素。

如果 #result 是顶级元素,

 <! -  #result作为顶级元素 - >
< D​​IV ID =结果>
  <跨度>文字< / SPAN>
< / DIV>
< D​​IV ID =等,顶级元素>< / DIV>
 

找到()将无法正常工作。相反,使用过滤器()

 变量$结果= $(响应).filter('#结果');
 

如果 #result 不是最高级别的元素,

 <! -  #result不是顶级元素 - >
< D​​IV>
  < D​​IV ID =结果>
    <跨度>文字< / SPAN>
  < / DIV>
< / DIV>
 

找到()将工作:

 变量$结果= $(响应).find('#结果');
 

Trying to find div element with id="result" in returned data from .ajax() using .find(). Unfortunately, alert(result) doesn't return div#result.

Here is my code:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        result = $(response).find("#result");
        alert(response); // works as expected (returns all html)
        alert(result); // returns [object Object]
    }
});

解决方案

To answer your question specifically, it seems to be working correctly. You said that it returns [object Object], which is what jQuery will return with the find("#result") method. It returns a jQuery element that matches the find query.

Try getting an attribute of that object, like result.attr("id") - it should return result.


In general, this answer depends on whether or not #result is the top level element.

If #result is the top level element,

<!-- #result as top level element -->
<div id="result">
  <span>Text</span>
</div>
<div id="other-top-level-element"></div>

find() will not work. Instead, use filter():

var $result = $(response).filter('#result');

If #result is not the top level element,

<!-- #result not as top level element -->
<div>
  <div id="result">
    <span>Text</span>
  </div>
</div>

find() will work:

var $result = $(response).find('#result');

这篇关于jQuery的.find()上()调用返回&QUOT来自阿贾克斯的数据; [对象的对象] QUOT;而不是DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆