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

Is using `innerHTML` the only way to create a `button` element in JavaScript with the `type` attribute?

本文关键字:元素 button 创建 方法 属性 唯一 是在 innerHTML JavaScript 使用 type      更新时间:2023-09-26

我想用下面的JavaScript制作一个按钮…

var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);

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

留言: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()吗?以下内容似乎可以在ie8中工作(没有在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>

根据您可能已经看到的这篇文章,IE7/8中的直接createElement DOM调用不适用于button元素,但它可以用于input

你可能是对的,innerHTML解决方案(和使用jQuery与HTML源代码,这在精神上几乎是一样的,IMHO)是唯一的方法。

关于IE7/8的DOM缺陷非常奇怪。非常有趣的发现!

使用innerHTML将元素中的所有内容替换为指定的内容。

jQuery .append()可以在IE7/8中工作(并且更容易)

$(document).ready(function() {
    $('body').append('<button type="button">I am a button</button');
});

这里有一个jsFiddle: http://jsfiddle.net/4ne48/

相关文章: