我使用JavaScript节点迭代器来创建附加到DOM中元素的对象实例。以下代码是我正在使用的代码,它可以正常工作:
var nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode: function(node) {
if (node.attributes['data-sd-autocomplete']
&& node.type === 'text')
return NodeFilter.FILTER_ACCEPT;
}
},
false
),
nodeList = [],
node;
SDAutoComplete.fields = [];
while (node = nodeIterator.nextNode())
nodeList.push(node);
// Add new instances of SDAutoComplete to the fields list
for (var i = 0; i < nodeList.length; i++) {
SDAutoComplete.fields.push(new SDAutoComplete(nodeList[i]));
}
我试图缩短代码以使其更简洁,删除for循环并替换while循环中的行,以便它直接用节点变量实例化:
while (node = nodeIterator.nextNode())
SDAutoComplete.fields.push(new SDAutoComplete(node));
但是这会导致页面挂起,好像while循环卡住一样。任何人都可以解释为什么会这样吗?