document.getElementsByTagName("a")缺少链接 [英] document.getElementsByTagName("a") misses a link

查看:107
本文介绍了document.getElementsByTagName("a")缺少链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Greasemonkey(FX7)编写脚本,试图删除某些链接,但发现由于某种原因,源中存在的,不是由JS隐藏或构造的一个未出现在数组中,该函数返回.

I was working on a script for Greasemonkey (FX7) trying to remove certain links and found out that for some reason one that was present in the source, not hidden or constructed by JS, didn't show up in the array that that function returns.

如果可以在运行该页面时通过JS构建该对象,这并不奇怪,但是它位于找到的另一个链接的后面.

If that one would have been constructed via JS upon running that page it wouldn't wonder me but it's sitting right behind another link that gets found.

所以有谁知道为什么会发生这种情况以及我如何解决呢?

So has anyone an idea why this is happening and how I could work around it?

var links = document.getElementsByTagName("a");
for (var l in links){
  if (links[l].href == "blah"){ ... }
}

这就是我尝试与他们合作的方式,由于我还有更多检查不碰到空值之类的东西,所以有点减少了.

Thats how I was trying to work with them, a bit cut down as I had some more checks to not run into nulls and such.

在旁注:我想知道为什么该函数还返回空条目.

On a sidenote: I was wondering why that function also returns null entries at all.

自从我寻求帮助以来,我就解决了这个问题,并找到了解决问题的好方法:

I passed this problem long since I asked for help and found a nice way to do it:

for (var i = 0, l; l = links[i]; i++) { }

这会一直将l设置为当前链接,直到没有剩余的链接为止.效果很好.

This keeps setting l to the current link until there aren't any left. Works nice.

推荐答案

for ... in语句循环遍历对象的属性.在这种特殊情况下,您要遍历Array对象的属性.尝试改用以下脚本:

The for...in statement loops through the properties of an object. In this particular case you are iterating over Array object properties. Try to use this script instead:

var links = document.getElementsByTagName("a");
for (var l = 0; l < links.length; l++){
  if (links[l].href == "blah"){ ... }
}

这篇关于document.getElementsByTagName("a")缺少链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆