在 $.AJAX 加载的 HTML 上使用 Jquery 选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/405409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Jquery Selectors on $.AJAX loaded HTML?
提问by jdee
I have
我有
$.ajax({
url: identity,
success: function(data) { ProcessIdentityServer(data) }
});
When 'data' is returned, is there a way to run selectors against it without adding it into the DOM. So for example, how can I get all the href values of any LINK tags contained in the HTML held in 'data' without adding it to the DOM first? Seems a shame to have to add it into the DOM if all I want to do is extract some stuff into an array. Anyone got any ideas?
当返回“数据”时,是否有一种方法可以针对它运行选择器而不将其添加到 DOM 中。例如,如何获取包含在“数据”中的 HTML 中包含的任何 LINK 标记的所有 href 值,而无需先将其添加到 DOM 中?如果我想做的只是将一些东西提取到数组中,那么不得不将它添加到 DOM 中似乎是一种耻辱。有人有任何想法吗?
采纳答案by Beau Simensen
// Finds all div elements within an XML document from an AJAX response.
$("div", xml.responseXML);
回答by stuartloxton
One note I will add which is from a similar problem on here is that if your AJAX returns the following:
我要添加的一个注释来自这里的类似问题,如果您的 AJAX 返回以下内容:
<div class="test">Hello</div>
<div class="one">World</div>
The following jQuery Won'twork:
下面的jQuery不工作:
$(data).find('div.test');
as the divs are top level elements and data isn't an element but a string, to make it work you need to use .filter
由于 div 是顶级元素,而数据不是元素而是字符串,要使其工作,您需要使用 .filter
$(data).filter('div.test');
回答by David Nyhuis
Before beginning, let's take a quick look at what jQuery does to a basic HTML page returned from an $.ajax()
call, and converting the returned data into a jQuery object.
在开始之前,让我们快速了解一下 jQuery 对$.ajax()
调用返回的基本 HTML 页面做了什么,并将返回的数据转换为 jQuery 对象。
$.ajax({
dataType : 'html',
url : 'path/to/example-page.html',
success : function(data) {
// log the result of the data converted into a jquery object.
console.log( $(data) );
}
});
Here's what you would expect to see:
以下是您希望看到的内容:
[
0 <TextNode textContent="\n\n\n\n\n ">
1 title
2 <TextNode textContent="\n ">
3 meta
4 <TextNode textContent="\n\n\n\n\n">
5 div#container
6 Comment { data=" #container ", length=12, nodeName="#comment", more...}
7 <TextNode textContent="\n\n">
jquery "1.6.4"
length 8
selector ""
// additional data and functions removed for brevity
]
YIKES!That's quite ugly! Attempting to do anything with that canyield results, but you need to know what the data structure looks like every single time, and where the data lie within that object. Is that data at the root, or is it buried within?
哎呀!实在是太丑了!尝试做任何事情都可以产生结果,但您需要知道每次的数据结构是什么样的,以及数据在该对象中的位置。这些数据是在根部,还是埋在其中?
Like previous posters have mentioned, you can use .filter()
, but the root is as far as that search will go, because you're simply filtering the returned results. However, if you were to use .find()
at this point and the element you wanted is at the root, you'll receive an empty set, but anything buried beyond the root will be found.
就像之前的海报提到的那样,您可以使用.filter()
,但根是搜索的范围,因为您只是过滤返回的结果。但是,如果此时您要使用.find()
并且您想要的元素在根处,您将收到一个空集,但会找到隐藏在根之外的任何元素。
So, why be pinned down to needing to know what that data structure looks like with 100% certainty, and why bother going through all the trouble of having to use multiple .filter()
and .find()
calls, and dare I say an .each()
loop? Yuck! That's just simply too much work and takes way too much time.
那么,为什么要确定需要 100% 确定地知道该数据结构是什么样的,为什么还要费心去经历必须使用多个.filter()
和.find()
调用的所有麻烦,我敢说是.each()
循环吗?糟糕!这只是太多的工作,需要太多的时间。
If you want to .find()
a particular HTML element returned from an .ajax()
call, start with the following line:
如果.find()
要从.ajax()
调用中返回特定的 HTML 元素,请从以下行开始:
var response = $('<html />').html(data);
Can it really be that easy? In fact, yes it is! What's happening here is that a new <html>
element is being created and converted into a jQuery object. This is used a starting location to insert the returned HTML from an .ajax()
call. It's kind of like doing $('html')
on a webpage. With this, you can begin finding elements.
真的有那么容易吗?事实上,是的!这里发生的事情<html>
是正在创建一个新元素并将其转换为 jQuery 对象。这是用于插入从.ajax()
调用返回的 HTML 的起始位置。这有点像$('html')
在网页上做。有了这个,您就可以开始查找元素了。
response.find( ... ); // any jquery selector in place of the ellipsis.
Here's an example that uses the original poster's question:
这是一个使用原始海报问题的示例:
$.ajax({
dataType : 'html',
url : 'path/to/example-page.html',
success : function(data) {
// set the returned contents in a new base <html> tag.
var response = $('<html />').html(data),
anchors, hrefValuesList = [ ],
i, end;
// now you can search the returned html data using .find().
anchors = response.find('a');
// grab all your href values from each anchor element.
end = anchors.length;
for (i = 0; i < end; i++) {
hrefValuesList.push( anchors[ i ].href );
}
// continue processing the data as necessary...
}
});
Obviously the above will need some refining if you want to filter out any unwanted content, or want to refine the values returned.
显然,如果您想过滤掉任何不需要的内容,或者想要优化返回的值,则上述内容需要进行一些优化。
With that, you could see something like the following example array returned:
这样,您可以看到类似于以下示例数组的返回:
[ "http://stackoverflow.com/", "http://www.google.com/" ] // and so on...
Using this approach, you can easily use the power of .find()
on any HTML data returned through the $.ajax()
function like you already do on any elements you find in the DOM. The real bonus is that you aren't directly manipulating the DOM to find or do what you want, which is an expensive process.
使用这种方法,您可以轻松地使用.find()
通过该$.ajax()
函数返回的任何 HTML 数据的强大功能,就像您已经在 DOM 中找到的任何元素上所做的那样。真正的好处是您不会直接操作 DOM 来查找或执行您想要的操作,这是一个昂贵的过程。
Happy scrubbing! =)
刷牙快乐!=)
回答by nakajima
Presuming that data
is a string of HTML, you can do this:
假设这data
是一串 HTML,你可以这样做:
$(data).find('a');
That will return the links without adding the data to the DOM.
这将返回链接而不将数据添加到 DOM。
回答by Michael
You have to define a container first, to be able to get/modify the elements from the response:
您必须先定义一个容器,才能从响应中获取/修改元素:
$.ajax({
url: url + "/ajax.htm",
dataType: "html",
success: function(html) {
container = $('#ajax_content');
container.html(html);
container.find("a").css("background","red");
}
});
回答by Brian Fisher
Sure you can use the $(data) function, one of the core jquery functions, to turn the returned html into DOM elements. Check out the docs online.
当然,您可以使用 $(data) 函数(jquery 核心函数之一)将返回的 html 转换为 DOM 元素。查看在线文档。
回答by simonhamp
You can also use context now (don't know when this was introduced):
现在也可以使用上下文(不知道是什么时候引入的):
$.get('some/url', '',
function (data) {
$("#domelement", data);
}
);
回答by Rel
This is the same as the accepted answer but with some extra explanation.
这与接受的答案相同,但有一些额外的解释。
You may use the jQuery contextparameter Link to docs
您可以使用 jQuery上下文参数链接到文档
I can't really explain better than the documentation.
我真的不能比文档更好地解释了。
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function
选择器上下文
默认情况下,选择器在 DOM 中从文档根开始执行它们的搜索。但是,可以通过使用 $() 函数的可选第二个参数为搜索提供替代上下文
The context parameter has been around since jQuery v1.0
context 参数从 jQuery v1.0 开始就存在了
Therefore a solution to the OP's example to "get all the href values of any LINK tags contained in the HTML held in 'data' without adding it to the DOM first" would be:
因此,OP 示例的解决方案是“获取包含在 'data' 中的 HTML 中包含的任何 LINK 标记的所有 href 值,而无需先将其添加到 DOM 中”:
success: function(data){
$("a", data).each(function(){
console.log( $(this).attr("href") );
});
}
回答by useful
my ultimate solution was
我的最终解决方案是
jQuery.ajax({
url: "/some-url",
cache: false,
dataType: "html",
success: function(data) {
jQuery("#target").html( jQuery(data).find('#ajax-data'));
}
});