使用`innerHTML`是用`type`属性在JavaScript中创建`button`元素的唯一方法吗?

ale*_*lex 3 javascript button

我想用以下JavaScript创建一个按钮...

var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);
Run Code Online (Sandbox Code Playgroud)

它工作得很好,除了IE7/8(我到目前为止所测试的所有内容).

消息:Object doesn't support this action
行:185
字符:9
代码:0
URI:http://example.com/widget.js

我发现了一个解决方法......

document.body.innerHTML = '<button type="button">I am button</button>';
Run Code Online (Sandbox Code Playgroud)

也就是说,设置innerHTML并让浏览器进行解析.

jsFiddle.

有没有其他方法可以在没有设置innerHTML属性的情况下在IE中使用它?

Cam*_*Cam 6

你试过.setAttribute()吗?以下似乎适用于IE 8(未在7中测试),Chrome,FF:

<html>
<body>
<script>
var button = document.createElement('button');
button.setAttribute('type','button')
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)