是否可以使用innerHTML将子标签插入<option>元素?

时间:2016-04-13 02:26:13

标签: javascript html google-chrome dom innerhtml

我工作的项目使用使用jQuery&#39; html()方法渲染到页面中的Mustache模板。

我注意到当我的模板添加到页面时,我在<option>标签内写的节点被其内部文本替换。但是,在使用createElementappendChild等DOM方法构建页面时,这不会发生。

我知道option elements only accept text as content。但我只使用<select>将其替换为自定义表单控件,该控件将每个innerHTML的{​​{1}}复制到<option>

此代码段模拟了相同的行为:

&#13;
&#13;
<div>
&#13;
// using DOM methods:
var select = document.createElement('select'),
		option = document.createElement('option'),
    strong = document.createElement('strong'),
    withDOM = document.getElementById('dom-methods'),
    withInnerHTML = document.getElementById('inner-html'),
    exampleHTML = '<select><option><strong>Hello</strong></option></select>';
    

strong.appendChild(document.createTextNode('Hello'));
option.appendChild(strong);
select.appendChild(option);
withDOM.appendChild(select);
withDOM.appendChild(
	document.createTextNode(select.innerHTML)
);

// using innerHTML
withInnerHTML.innerHTML = exampleHTML;
withInnerHTML.appendChild(
	document.createTextNode(withInnerHTML.innerHTML)
)
&#13;
select { display: block }
&#13;
&#13;
&#13;

0 个答案:

没有答案
相关问题