Uncaught TypeError: Cannot set property 'value' of null with custom element
Uncaught TypeError: Cannot set property 'value' of null with custom element
我创建了一个 web 组件并给了它一个方法。按下按钮时我希望该方法显示 "Hello" 但它根本不起作用,我收到以下错误:
Uncaught TypeError: Cannot set property 'value' of null
我想知道为什么会这样,我该如何解决?
我的JS代码:
var WC = Object.create(HTMLElement.prototype);
WC.hi= function() {
document.getElementById("w-c").value = "Hello!";
};
var WCR = document.registerElement("w-c", {
prototype: WC,
extends:'input'
});
var wc = new WCR();
var division = document.getElementById('sh');
var root = division.createShadowRoot();
root.appendChild(wc);
WC.setDimensions = function() {
Object.defineProperty(WC, 'height', {value: 1000});
};
我的HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>WEB COMPONENT</h2>
<div id="sh"> </div>
<script src="webcomponent.js"> </script>
<button onclick="wc.hi()">
Say hi</button>
</body>
</html>
id 为"w-c" 的元素不存在。创建它,或使用 document.createElement
编辑:
var newEl = document.createElement("div");
/*apply styles here*/
newEl.id = "w-c";
document.appendChild(newEl);
我创建了一个 web 组件并给了它一个方法。按下按钮时我希望该方法显示 "Hello" 但它根本不起作用,我收到以下错误:
Uncaught TypeError: Cannot set property 'value' of null
我想知道为什么会这样,我该如何解决?
我的JS代码:
var WC = Object.create(HTMLElement.prototype);
WC.hi= function() {
document.getElementById("w-c").value = "Hello!";
};
var WCR = document.registerElement("w-c", {
prototype: WC,
extends:'input'
});
var wc = new WCR();
var division = document.getElementById('sh');
var root = division.createShadowRoot();
root.appendChild(wc);
WC.setDimensions = function() {
Object.defineProperty(WC, 'height', {value: 1000});
};
我的HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>WEB COMPONENT</h2>
<div id="sh"> </div>
<script src="webcomponent.js"> </script>
<button onclick="wc.hi()">
Say hi</button>
</body>
</html>
id 为"w-c" 的元素不存在。创建它,或使用 document.createElement
编辑:
var newEl = document.createElement("div");
/*apply styles here*/
newEl.id = "w-c";
document.appendChild(newEl);