比如说,我需要在自定义元素中调用一个函数,这样当 slider 在该元素中移动时,文本会得到更新(仅针对该元素)。 main.js
文件,
class OninputClassDemo extends HTMLElement {
constructor(){
super();
const shadow = this.attachShadow({mode:'open'});
this.parent = document.createElement('div');
this.slider = document.createElement('input');
this.slider.setAttribute('type','range');
this.slider.setAttribute('min','0');
this.slider.setAttribute('max','99');
this.slider.setAttribute('value','0')
this.text = document.createElement('input');
this.text.setAttribute('type','text');
this.text.setAttribute('value','');
this.parent.appendChild(this.slider);
this.parent.appendChild(this.text);
shadow.appendChild(this.parent);
this.slider.setAttribute('oninput','OninputClassDemo.changeValue()');
}
changeValue = function(){
this.text.setAttribute('value',this.slider.getAttribute('value'));
}
}
window.customElements.define('demo-element',OninputClassDemo);
在模板方面,
<!DOCTYPE html>
<html lang="en">
<head>
<script src="main.js"></script>
</head>
<body>
<demo-element></demo-element>
</body>
</html>
我得到的错误是,
OninputClassDemo.changeValue is not a function
at HTMLInputElement.oninput
我不知道如何在
this.slider.setAttribute('oninput','WhatShouldIPutHere')
中引用该特定对象的方法,以便仅更改该对象的文本框。
最佳答案
您应该使用 addEventListener 绑定(bind)事件监听器。您应该使用 this 绑定(bind)到方法,而不是类名。设置 value 属性,不设置属性。
class OninputClassDemo extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({
mode: 'open'
});
this.parent = document.createElement('div');
this.slider = document.createElement('input');
this.slider.setAttribute('type', 'range');
this.slider.setAttribute('min', '0');
this.slider.setAttribute('max', '99');
this.slider.setAttribute('value', '0')
this.text = document.createElement('input');
this.text.setAttribute('type', 'text');
this.text.setAttribute('value', '');
this.parent.appendChild(this.slider);
this.parent.appendChild(this.text);
shadow.appendChild(this.parent);
this.slider.addEventListener('input', (event) => this.changeValue());
}
changeValue() {
this.text.value = this.slider.value;
}
}
window.customElements.define('demo-element', OninputClassDemo);
<demo-element></demo-element>
关于Javascript 自定义元素的 oninput 函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61818576/