【发布时间】:2015-06-02 23:55:55
【问题描述】:
我正在尝试在 html 文档中搜索 dl 并返回/存储它们的 'id' 属性。但是,当我包含一个链接的“每个”函数时,什么都找不到,并且当我执行一个“查找”函数调用时,id 属性返回为未定义,即使它不是。这就是我搜索的 html 的样子:
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>blah Resources</title>
<link href="blah" rel="stylesheet" type="text/css">
<style type="text/css"></style></head>
<body cz-shortcut-listen="true">
<span>Resources</span>
<dl id="/data/file.docx">
<dt>Name</dt>
<dd>blah</dd>
<dt>URL</dt>
<dd>blah</dd>
<dt>Last-Modified</dt>
</dl>
<dl id="/data/app.js">
<dt>Name</dt>
<dd>app.js</dd>
<dt>URL</dt>
<dd>blah</dd>
</dl>
<dl id="/data/date.txt">
<dt>Name</dt>
<dd>blah</dd>
</dl>
</body>
</html>
我的代码是这样的(ajax调用没问题,成功了):
function processHTML(html){
alert("processHTML was called");
$(html).find('dl').each(function(){
var url = $(this).attr('id');
alert(url);
});
};
在上面的代码中,没有任何警报。在下面的代码中,警告的内容只是“未定义”。
function processHTML(html){
alert("processHTML was called");
var url = $(html).find('dl').attr('id');
alert(url);
};
我做错了什么?
编辑: 作为比较,以下代码工作得非常好,并且驻留在我拥有的不同 js 文件中,我很难看到这个工作示例和我上面的非工作示例之间的区别。
鉴于此 html 文档:
<html><head>
<title>blah</title>
<LINK href="resources.css" rel="stylesheet" type="text/css"/>
</head><body>
<span>Resources</span> <dl id="tool">
<dt>Name</dt>
<dd>Tool1</dd>
<dt>URL</dt>
<dt>Created</dt>
<dd>date</dd>
</dl>
<dl id="tool">
<dt>Name</dt>
<dd>Tool2</dd>
<dt>URL</dt>
<dt>Created</dt>
<dd>date</dd>
</dl>
</body>
</html>
这段代码运行良好:
function processHTML(html){
var name = "";
var url;
$(html).find('dt').each(function(){
var property = $(this).text();
if(property == "Name"){
var temp = $(this).next().text();
name = "";
}
alert(name);
}
};
警报:
工具1
工具2
【问题讨论】:
-
你检查过你在 html 变量中得到响应了吗?
标签: javascript jquery html ajax html-parsing