为了账号安全,请及时绑定邮箱和手机立即绑定

为啥在使用appendChild时不使用var变量就没法工作?

为啥在使用appendChild时不使用var变量就没法工作?

慕仰0923016 2016-10-07 12:51:10
以下代码正常工作:function charu(){ var para=document.createElement("p"); var txt=document.createTextNode("我的世界"); document.getElementsByTagName("body")[0].appendChild(para); para.appendChild(txt);以下代码不工作:function charu(){ document.getElementsByTagName("body")[0].appendChild(document.createElement("p")); document.createElement("p").appendChild(document.createTextNode("我的世界"));按理说,它们应该完全等同啊?
查看完整描述

2 回答

已采纳
?
stone310

TA贡献361条经验 获得超191个赞

这里不工作的代码写成了2句,第一句执行完并未被储存,然后执行第二句,所以这里第二句和第一句没有任何关系;

所以不能分成2距,连着写,就是等价的:

document.getElementsByTagName("body")[0].appendChild(document.createElement("p")).appendChild(document.createTextNode("我的世界"));


查看完整回答
1 反对 回复 2016-10-07
  • 慕仰0923016
    慕仰0923016
    谢谢,真是这个问题,看样子以后要加变量就能预防这类问题。。。。
  • 慕仰0923016
    慕仰0923016
    那为啥这样也不工作?。。。。。。。 function charu(){ var para=document.createElement("p"); document.getElementsByTagName("body")[0].appendChild(document.createElement); para.appendChild(document.createTextNode("我的世界")); } 只能变成这样就能工作: function charu(){ var para=document.createElement("p"); document.getElementsByTagName("body")[0].appendChild(para); para.appendChild(document.createTextNode("我的世界")); }
  • 慕仰0923016
    慕仰0923016
    我写在下面了
?
慕仰0923016

TA贡献2条经验 获得超0个赞

这样也不工作?。。。

function charu(){

var para=document.createElement("p");

document.getElementsByTagName("body")[0].appendChild(document.createElement("p"));

para.appendChild(document.createTextNode("我的世界"));

}


查看完整回答
反对 回复 2016-10-07
  • stone310
    stone310
    一样的,你这里第一句跟第二句没有关系; 这里执行完para已经是带有“我的世界”的P标签,即<p>我的世界</p>; 但是body.appendChild方法添加的并不是para,而是一个空的<p>标签; para虽然已经创建了,但并没有添加到body上,反而是添加了一个空的P到body上
  • 慕仰0923016
    慕仰0923016
    刚刚看到,谢谢,我慢慢理解理解
  • 2 回答
  • 0 关注
  • 1381 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信