实际上我需要这个来用更简单的方式处理“选项”元素,更简单的正则表达式。innerHTML = append content
如果用于select
元素,则 ie 的 Cos 不会附加。附加操作在下面的链接中提到,但不适用于选项元素。然后我找到了解决这个问题的方法。如果追加内容是选项或选项,则使用handleOptionElements
,如果不使用asyncInnerHTML
。
function append(el, child) {
if (child.nodeType === 1 || child.nodeType === 3) {
// Without clone, removes element if it is copied from document
return el.appendChild(child.cloneNode(true));
}
content = trim(content);
if (content.substring(0, 7) === "<option" &&
content.substring(content.length - 7) === "option>") {
handleOptionElements(content, el);
} else {
el.innerHTML = content;
}
return el;
}
http://james.padolsey.com/javascript/asynchronous-innerhtml/
为 innerHTML 设置大值时提高性能的方法
var re_standaloneAttributes = /^(select|disabl)ed$/i,
re_optionSearch = /<option\s*([^>]*)>(.*?)<\/option>/gi,
re_attributeSearch = /([^\s]*)=["'](.*?)["']|([\w\-]+)/g;
function handleOptionElements(content, targetElement) {
var options = [], attributes = [],
optionElement, optionElements = [], createOption;
(""+ content).replace(re_optionSearch, function(src1, attr, text) {
if (!src1) return;
(""+ attr).replace(re_attributeSearch, function(src2, name, value) {
if (!src2) return;
name = name || src2;
value = value || (value = re_standaloneAttributes.test(name) ? name : "");
attributes.push({name: name, value: value});
});
options.push({text: text || "", attributes: attributes});
// Reset attributes for each element
attributes = [];
});
createOption = (function() {
var option = document.createElement("option");
return function() { return option.cloneNode(true) };
})();
forEach(options, function(option) {
optionElement = createOption();
// optionElement.text doesn't work on ie 7-8
optionElement.textContent = optionElement.innerText = option.text;
forEach(option.attributes, function(attribute) {
optionElement.setAttribute(attribute.name, attribute.value);
});
if (targetElement !== undefined) {
targetElement.appendChild(optionElement);
} else {
optionElements.push(optionElement);
}
});
return optionElements;
}