这是 JavaScript 的逐步执行过程。
我有一个 HTMLCollection,我想循环遍历它并提取 ID 为 FileUploadControl 的对象。我该怎么做?
这是我的代码,我该如何继续?
function uploadImage(lnk)
{
var row = lnk.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var abc = row.cells[2].getElementsByTagName("input");
var arr = [].slice.call(abc);
}
最佳答案
这样就可以了:
abc.namedItem('FileUploadControl')
但请注意:
Different browsers behave differently when there are more than one elements matching the string used as an index (or namedItem's argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another HTMLCollection and Opera returns a NodeList of all matching elements.
来自here .
这意味着如果您的标记中有这样的内容:
<div id='id'>Foo</div>
<div id='id'>Bar</div>
执行以下代码时浏览器的行为会有所不同:
document.getElementsByTagName('div').namedItem('id')`
Firefox 将返回 HTMLElement ,而 IE 将返回另一个 HTMLCollection。
为了解决这种不一致问题,您可以应用一个函数来返回相同的对象。
retElement( abc.namedItem('id') );
可能是这样的:
var retElement = function(oElem) {
//Firefox
if (oElem instanceof window.HTMLElement)
return oElem;
//IE and WebKit
if (oElem instanceof window.HTMLCollection)
return oElem.item(0);
};
关于javascript - 如何从 HTML 集合中提取名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281268/