开发者

How to grab class names and attributes from ajax loaded html

I am loading pages via ajax and need to grab a certain class from the parsed html. The method I'm using doesn't seem to work and only returns 'undefined'.

  $.ajax({
    type:'post',
    url:"path/to/page",
    success:function(r){
      r = $(r);//parse ht开发者_如何学运维ml
      var page = r.find('#siteWrap').attr('class');//pull off class name
      alert(page);//returns "undefined"
    }
  });

Love some help guys!


try to add your data (r) to the dom:

$(body).append('<div id="appended">'+r+'</div>); and then do something like this: $('#appended').find(....)

if you want to not show the data in R just hide #appended via css i.e. #appended{display: none;} and remove it after your parsing $('#appended').remove()


It looks like just a typo; try changing the $r.find to r.find


Well looks like $r is undefined.

r = $(r);//parse html

$r is still undefined.


I solution I came up with (inspired by @helle):

I put a new element on the page I am requesting,

<div id='page' style='display:none;'>myPage</div>

I then use jQuery to pull the html out from between those tags in the response data:

  $.ajax({
    type:'post',
    url:$path,
    data:{ajaxRequest:'true'},
    success:function(r){
      var $r = $(r);
      var $page = $r.find('#page').html();
      alert($page);//alerts "myPage"!
    }
  });

Conclusion: You can not pull attributes or class names from ajax html responses once parsed by jquery, only html() can be pull out of parsed html data.

Hope this helps someone out!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜