javascript - IE7中的getElementsByName

标签 javascript dom internet-explorer-7

我有一些代码可以做到这一点:

 var changes = document.getElementsByName(from);
 for (var c=0; c<changes.length; c++) {
   var ch = changes[c];
   var current = new String(ch.innerHTML);
   etc.
 }

这在 FF 和 Chrome 中工作正常但在 IE7 中不工作。大概是因为 getElementsByName 在 IE 中不起作用。最好的解决方法是什么?

最佳答案

如果您不知道为什么这在 IE 中不起作用,这里是 the MSDN documentation on that function :

When you use the getElementsByName method, all elements in the document that have the specified NAME attribute or ID attribute value are returned.

Elements that support both the NAME attribute and the ID attribute are included in the collection returned by the getElementsByName method, but elements with a NAME expando are not included in the collection; therefore, this method cannot be used to retrieve custom tags by name.

Firefox 允许 getElementsByName()检索使用 NAME expando 的元素,这就是它起作用的原因。这是否是一件好事™ 可能有争议,但这就是现实。

因此,一种选择是使用 getAttribute() DOM 方法请求 NAME 属性,然后测试该值以查看它是否是您想要的,如果是,则将其添加到数组中。但是,这需要您遍历页面中的所有节点或至少在一个小节中,这不是最有效的。您可以使用 getElementsByTagName() 之类的东西预先限制该列表也许吧。

如果您控制页面的 HTML,另一种方法是为所有感兴趣的元素提供一个仅随数字变化的 Id,例如:

<div id="Change0">...</div>
<div id="Change1">...</div>
<div id="Change2">...</div>
<div id="Change3">...</div>

然后有这样的 JavaScript:

// assumes consecutive numbering, starting at 0
function getElementsByModifiedId(baseIdentifier) {
    var allWantedElements = [];
    var idMod = 0;
    while(document.getElementById(baseIdentifier + idMod)) { // will stop when it can't find any more
        allWantedElements.push(document.getElementById(baseIdentifier + idMod++));
    }
    return allWantedElements;
}

// call it like so:
var changes = getElementsByModifiedId("Change");

当然,这是一种 hack,但它可以完成您需要的工作,而且与其他一些 hack 相比效率也不会太低。

如果您使用的是某种 JavaScript 框架/工具包,您的选择会好得多,但我没有时间讨论这些细节,除非您表明您正在使用。就我个人而言,我不知道人们在没有它的情况下如何生活,它们节省了如此多的时间、精力和挫败感,以至于你负担不起使用它。

关于javascript - IE7中的getElementsByName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/278719/

相关文章:

javascript - 如何触发 :hover transition that includes three overlapping div elements (Venn diagram)

javascript - Firefox 扩展的 'load event' 之前的事件?

javascript - 在函数参数中分配变量是如何工作的?这样做的目的是什么?

javascript - 如何使用附加的 HTML 淡入 div

javascript - 是否有任何工具可以从我的 JavaScript 代码中检测/避免 IE 专有语法?

javascript - 在 IE7 中加载外部 Javascript 文件的问题

javascript - 自动完成 UI 问题

javascript - 粘贴后如何保持文本突出显示?

javascript - 在nodejs + xpath中获取node

css - 为什么我的文本在 IE7 中被截断了?