我正在尝试通过Ajax调用从here获取一些数据。我可以在我的控制台中获取整个文档,但我不知道如何获取单个元素。我想要标题和下面的内容。
<script>
$(function() {
$.ajax({
url: 'http://feeds.reuters.com/reuters/technologyNews',
type: 'GET',
dataType: 'html',
success: function(data) {
console.log(data); //This works
//How to find titles and content underneath?
$('itemcontent').each(function() { //This does not work
var itemcontent = $(this).text() + '<br>';
console.log(itemcontent);
})
}
});
})
</script>
“‘itemcontent”是标题下面的文本。抓取这些元素中的文本的正确语法是什么?
更新我现在可以取回数据了,但只有一次。我没有正确使用.each()或其他语法吗?最奇怪的是,它得到的是的最后一个元素,而不是第一个。
$.ajax({
url: 'http://feeds.reuters.com/reuters/technologyNews',
type: 'GET',
dataType: 'html',
success: function(data) {
console.log(data);
$(data).find('.itemcontent').each(function() { //I'm only getting one result back
var text = $(this).text();
$('#rss').html('<p>' + text + '</p>');
})
}
这是我得到的结果,页面上的最后一个'.itemcontent‘文本:
Sonos Inc, a maker of hi-tech wireless speakers, filed for an initial public offering on Friday, riding on the back of increasing popularity of streaming music through smartphone apps on connected audio systems.
发布于 2018-07-10 22:36:41
问题1
您需要将返回的数据加载到元素中,以便像尝试使用$(data).find(SELECTOR)
一样对其进行处理
问题2
Each将数组作为第一个参数$.each(array, function(index, element){});
$.ajax({
url: 'http://feeds.reuters.com/reuters/technologyNews',
type: 'GET',
dataType: 'html',
success: function(data) {
console.log(data);
$.each($(data).find('.itemcontent'),function() {
var text = $(this).text();
$('#rss').html('<p>' + text + '</p>');
});
}
});
问题3
您只是将#rss
的内容替换为数组的每次迭代,这只会导致元素中只有最后一个结果。如果你想要它们,你应该是#rss
的appending
元素。例如,$("#rss").append($("<p>").html(text));
发布于 2018-07-10 05:58:18
您的问题是您正在寻找一个标签,而不是一个类。你需要有
$('.itemcontent').each(function() {
此外,您必须将url称为https,而不是http。它为我抛出了一个错误
https://stackoverflow.com/questions/51254469
复制相似问题