问题
I want to loop thru a file which is loaded with ajax, but it won't loop, i have tried a couple of things but I cant get it to work.
// jquery
$.ajax({
url: 'file.html',
type: "GET",
dataType: "html",
success: function(data) {
$(data).find('div').each(function(i){
alert('found')
});
},
error: function(){
alert('oeps...')
}
});
// file.html
<div>
// content goes here
</div>
<div>
// content goes here
</div>
<div>
// content goes here
</div>
...
...
回答1:
You need to change .find
to .filter
. This is because .find
searches the children descendants of all the elements, but since your html file is just <div>
s, you need to use .filter
to find them.
DEMO: http://jsfiddle.net/zuPVp/
回答2:
You dont need to specify html
as the datatype, it is not needed.
SO, remove the following line.
dataType: "html"
回答3:
The reason that doesn't work is because .find looks for descendants in data, all of those divs are at the root.
You can create an empty div then set the html of that div to your data. This will ensure find works as the divs will then be descendants.
$.ajax({
url: 'file.html',
type: "GET"
success: function(data) {
$('<div/>').html(data).each(function(index, item) {
console.log(item);
});
},
error: function(){
console.log('error')
}
});
Or you could use filter.
$.ajax({
url: 'file.html',
type: "GET"
success: function(data) {
$(data).filter('div').each(function(index, item) {
console.log(item);
});
},
error: function(){
console.log('error')
}
});
回答4:
It's hard to know what you are trying to do, but I'm guessing it's this:
$.ajax({
url: 'file.html',
type: "GET"
success: function(data) {
$.each($('div', data.outerHTML), function(index, item) {
console.log(item);
});
},
error: function(){
console.log('error')
}
});
回答5:
In this case, .find()
does not work because the HTML you are searching does not contain any div
children nodes. To fix this, first append the items to some container and then use .find()
.
http://jsfiddle.net/jbabey/hvkw9/1/
var html = $('<div>first div</div><br /><div>second div</div>');
// 0, no child divs in html
console.log(html.find('div').length);
// 2, now the divs in html are children of an intermediate div
console.log($('<div>').append(html).find('div').length);
来源:https://stackoverflow.com/questions/10589703/jquery-ajax-cant-loop-thru-the-found-data