我想用以下 JavaScript 制作一个按钮...
var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);
效果很好,除了在 IE7/8 中(我目前测试过的所有内容)。
Message:
Object doesn't support this action
Line:185
Char:9
Code:0
URI:http://example.com/widget.js
我找到了解决方法...
document.body.innerHTML = '<button type="button">I am button</button>';
也就是设置innerHTML
,让浏览器来解析。
jsFiddle .
有没有其他方法可以在不设置 innerHTML
属性的情况下让它在 IE 中工作?
最佳答案
你试过.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>
关于javascript - 使用 `innerHTML` 是在具有 `button` 属性的 JavaScript 中创建 `type` 元素的唯一方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7238735/