我有一个简单的 JavaScript 抓取工具,用于本地页面。
我会找到所有“title”类元素的 id 属性。
问题是,当我在屏幕上打印变量时,变量(title1)永远是“未定义”,而不是像它必须的那样“xxx”。
出了什么问题?
本地页面:
<!DOCTYPE HTML>
<html>
<body>
<div class="title" id="xxx"> xyz</div>
</body>
(部分)代码:
{
$.get("http://localhost/new.php", function(html) {
var title1 = $(html).find(".title").attr("id");
document.getElementById("1").innerHTML = title1;
})
}
最佳答案
这是因为 .title
是一个直接元素..您可以使用 $(html).filter('.title').attr('id')
或将 .title
div 包裹在另一个 div 内
var html = '<div class="title" id="xxx"> xyz</div>';
alert($(html).filter('.title').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
换行div
var html = '<div><div class="title" id="xxx"> xyz</div><div>';
alert($(html).find('.title').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
工作示例
var html = '<div class="title" id="xxx"> xyz</div>';
var FindId = $(html).filter('.title').attr('id');
$('#1').html(FindId);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1"></div>
关于Javascript scraper 按类名查找元素属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47846719/