Why does appendChild only work when I remove the docType

早过忘川 提交于 2019-12-25 04:56:16

问题


When I put any sort of doctype declaration like <!DOCTYPE html >, appendChild does not work.... Why?

<form>
<script language="javascript">
    function function2() {
        var myElement = document.createElement('<div style="width:600; height:200;background-color:blue;">www.java2s.com</div>');
        document.forms[0].appendChild(myElement);
    } 
</script>


<button onclick="function2();"></button>

</form>

I'm trying to get data from a popup window's parent opener...is that possible? The data can be a string literal or value tied to the DOM using jQuery .data()


回答1:


If you're having this problem in IE, it's probably because the presence of a DOCTYPE declaration forces the browser into "standards-compliance" mode. This can cause code that doesn't conform to expected standards to break.

In your case, it's probably because document.createElement doesn't accept an HTML fragment - it accepts an element name, e.g. document.createElement('div').

Try replacing your function body with something like this:

var myElement = document.createElement('div');
myElement.style.width = '600px';
myElement.style.height = '200px';
myElement.style.backgroundColor = 'blue';
myElement.appendChild(document.createTextNode('www.java2s.com'));
document.forms[0].appendChild(myElement);

Read up on the document object model here: https://developer.mozilla.org/en/DOM

Also, jQuery is good for easily creating elements using the syntax you specified.



来源:https://stackoverflow.com/questions/3209621/why-does-appendchild-only-work-when-i-remove-the-doctype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!