更新:请尝试下面的代码,我在其中添加了一个绑定语句来绑定“this”
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
document.querySelector('xmp-1').action1 = function(){
console.log("this is the callback");
};
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super();
this.handler = this.handler.bind(this);
}
handler() {
console.log("this is the test");
console.log('test action');
this.action1();
}
connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click',this.handler);
}
});
</script>
</body>
</html>
请在您的代码中将 xmp-1更改为#test,如下所示,
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
window.addEventListener('load', (event) => {
document.querySelector('#test').action1 = function(){
console.log("this is the callback");
};
});
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super(); }
connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click', function () {
console.log('test action');
this.action1();
});
}
});
</script>
</body>
</html>
或者请尝试如下所示的方法 2,您必须在其中添加一个名为this.querySelector('#test').action1的函数到您的自定义元素。
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super(); }
connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click', function () {
console.log('test action');
this.action1();
});
this.querySelector('#test').action1 = function() {
console.log('test action1');
}
}
});
</script>
</body>
</html>