href属性集,javascript看作空字符串

时间:2015-07-24 22:07:12

标签: javascript html dom

我在Chrome中遇到奇怪的行为(v43.0.2357.134),我正在读取锚元素的.href属性,但在特定情况下,其值为空字符串。

我希望在所有锚点上填充.href值。

问题

具体来说,这就是所观察到的:

//Bad (unwanted) behaviour
var currentElem = ; //Code to pick out an anchor element
console.info(currentElem.href); //"" (empty string)
console.info(currentElem.getAttribute('href'); //"path/to/other/page.html"

enter image description here

编辑添加/澄清:请注意,在此屏幕截图中,在到达第四行代码时,nextPageUri的值为空字符串(否则不会达到{{1行)。然后第五行使用debugger;值填充nextPageUri,因此显示在第二行旁边的值。

这是(正确)在Firefox中看到的,以及通过Chrome的前两个DOM:

.getAttribute('href')

背景

上下文:这是在将多个搜索结果页面内联到单个页面的脚本中,并且锚元素位于通过//Good (desired) behaviour var currentElem = ; //Code to pick out an anchor element console.info(currentElem.href); //"http://example.org/root/dir/path/to/other/page.html" console.info(currentElem.getAttribute('href'); //"path/to/other/page.html" 检索的DOM中。该代码通过Firefox完美运行,大于100页。

令人困惑的是,上述错误行为仅发生在Chrome浏览器中的第三个及后续请求中。

3 个答案:

答案 0 :(得分:1)

这是基于Chromium / Blink的浏览器的问题:如果使用DOMParser将字符串解析为文档,则href属性具有相对URI(即不以http [s]开头) )将被解析为空字符串。

Chromium issue 291791引用tkent:

  

那是因为DOMParser创建的文档没有baseURI。如果没有baseURI,则假定相对URI引用无效。

如果您使用createHTMLDocument,也会发生同样的事情。 (Chromium issue 568886

此外,基于this test code posted by scarfacedeb on Githubsrc属性也表现出与相对URI相同的行为。

正如您所指出的,使用getAttribute()代替点符号可以正常工作。

答案 1 :(得分:0)

Chrome" element.href"在第3次尝试时没有采取任何不同的行为,而不是在前2次 - 你提到你正在分页,当这个错误发生时。如何" href"每次到达页面时,下一页链接的属性都会被设置?在设置href之前,评估元素的href属性的代码似乎只是在运行之前运行 - 调试器可以在暂停后对其进行评估。

尝试在plunkr中重现此问题。

答案 2 :(得分:0)

我知道您正在检查nextPageUri是否为空。

但是,你可以尝试一直使用

:@account.to_s == '@account'

看看是否有效?

我遇到了类似的问题,使用DOMParser翻译来自ajax请求的nextPageUri = currentElem.getAttribute('href'); 页面,然后在其中查找text/htmlhref个元素。< / p>

出于说明目的,这就是我使用解析器

的方式
<a>

自己测试

如果您想自己测试var parser = new DOMParser(); $.ajax({....}).done(function(request){ var page = parser.parseFromString(request, 'text/html'); }); .href的行为,请在chrome dev工具控制台上运行此代码:

.getAttribute("href")