我在学习webpack构建项目的时候,想做一个小的demo,就是现在hello.js中定义一个login界面,然后再index.js中引用。发现hello.js中函数return的元素节点,在index.js中运行不了,难道是两个js文档里的元素节点不可以互相调用。但是我发现在同一个js文件中定义的函数返回元素节点就可以被当前的appendChild()调用。所以很疑惑,为什么调取另一个js中的元素节点却不行。
两个js情况。
index.js
import { lg } from './hello.js';
document.body.appendChild(lg);
hello.js
export function lg() {
var login = window.document.createElement('div');
login.style.height = "300px";
login.style.width = "300px";
login.style.backgroundColor = "#69ecf4"
let name = document.createElement('input');
name.style.width = "180px";
name.style.height = "110px";
name.style.backgroundColor = "#69ecf4";
let password = document.createElement('input');
password.style.width = "180px";
password.style.width = "110px";
name.style.backgroundColor = "#69ecf4";
login.appendChild(name);
login.appendChild(password);
return login;
}
单个js
index.js
function component() {
var element = document.createElement('pre');
element.innerHTML = [
'Hello webpack!',
'5 cubed is equal to ' + cube(5)
].join('\n\n');
return element;
}
document.body.appendChild(component());
两个js情况的结果
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at ./src/index.js (index.js:10:1)
at webpack_require (bootstrap:24:1)
at startup:6:1
at startup:6:1
单个情况结果正常
appendChild 调用它的对象必须是 node类型也就是 dom元素。 index.js 第10行附近 你打印一下调用 appendchild的对象是不是 dom节点