jQuery Ajax通过返回html解析 [英] Jquery ajax parse through return html
问题描述
如何在ajax html响应中找到名为findThis的元素?我什至找不到第一个孩子(错误消息:对象不支持属性或方法第一个")
How do I find an element named findThis in the ajax html response? I can't even find the first child (Error message: Object doesn't support property or method 'first')
$.ajax({
type: "GET",
url: www.someWebSite.com,
contentType: "application/x-www-form-urlencoded",
dataType: "text/html",
success: function (html) {
var topHtml= $(html).first();
}
});
我正在使用Jquery 1.8.2
I am using Jquery 1.8.2
推荐答案
今天因完全相同的问题而rug草.经过几个令人沮丧的小时,我在所有情况下都发现了以下作品.具有这样的部分的HTML文件:
Strugled today with the exact same problem. After some frustrating hours I found out the following works in all occasions. Having a HTML file with sections like this :
...
<h4>headline</h4>
<p id="id">Lorem ipsum dolor sit amet ...</p>
...
我只是想查找具有特定ID的<p>
的内容,并将该p
的内容附加到元素上的属性.
I just wanted to look up the content of a <p>
with a certain id and attach the content of that p
to an attribute on an element.
$.ajax({
dataType: "html",
url : 'path/to/html.html',
success : function(html) {
var div = $('<div>');
div.html(html);
var content = div.find('#id');
$("#element").attr('attribute', content.html());
}
});
创建一个虚拟元素<div>
,为该div
分配HTML响应;从div
中找到所需的内容,然后用html()
提取.
Create a dummy element <div>
, assign the HTML-response to that div
; find the desired content from the div
, extract it with html()
.
jQuery似乎很难解析即时HTML.特别是如果标记搞砸了.我们必须遍历一个虚拟元素并解析该内容以获得所需的内容.
jQuery seems to have a hard time parsing on-the-fly HTML. Especially if the markup is messed up. We must go through a dummy element and parse the content of that to get what we want.
我见过的所有其他解决方案都建议解析到HTML节点,仅返回空元素或完全不返回任何内容.以上似乎是要走的路.
All other solutions I have seen suggest parsing to HTML-nodes, does only return the empty element or does not return anything at all. The above seems to be the way to go.
这篇关于jQuery Ajax通过返回html解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!