I wanted to make a button with the following JavaScript...
var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('开发者_JAVA技巧I am button'));
document.body.appendChild(button);
It works great, except in IE7/8 (all I have tested so far).
Message:
Line:Object doesn't support this action
185
Char:9
Code:0
URI:http://example.com/widget.js
I found a workaround...
document.body.innerHTML = '<button type="button">I am button</button>';
That is, set innerHTML
and let the browser do the parsing.
jsFiddle.
Is there any other way to get this to work in IE without setting the innerHTML
property?
Have you tried .setAttribute()
? The following appears to work in IE 8 (didn't test in 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>
According to this article which you might have seen, the direct createElement
DOM call in IE7/8 does not work with the button
element, but it does work with input
.
You may be right about innerHTML
solutions (and the use of jQuery with HTML source, which is in spirit pretty much the same thing, IMHO) being the only approach.
Very strange about the DOM deficiency in IE7/8. Very interesting find!
Using innerHTML
replaces everything in the element with what you specify.
jQuery .append()
works in IE7/8: (and it is much easier)
$(document).ready(function() {
$('body').append('<button type="button">I am a button</button');
});
Here's a jsFiddle: http://jsfiddle.net/4ne48/
精彩评论