为什么只有我删除docType时appendChild才能工作 [英] Why does appendChild only work when I remove the docType

查看:116
本文介绍了为什么只有我删除docType时appendChild才能工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我放置任何类型的文档类型声明(如<!DOCTYPE html >)时,appendChild都无法工作....为什么?

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>

我正在尝试从弹出窗口的父打开器中获取数据...可能吗?数据可以是字符串文字,也可以是使用jQuery .data()绑定到DOM的值

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()

推荐答案

如果您在IE中遇到此问题,可能是因为DOCTYPE声明的存在迫使浏览器进入符合标准"模式.这可能会导致不符合预期标准的代码被破坏.

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.

在您的情况下,可能是因为document.createElement不接受HTML片段-它接受一个元素名称,例如document.createElement('div').

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);

在此处阅读文档对象模型: https://developer.mozilla.org/en/DOM

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

此外, jQuery 有助于轻松使用您指定的语法创建元素.

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

这篇关于为什么只有我删除docType时appendChild才能工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆