Javascript 自定义元素的 oninput 函数问题

标签 javascript

比如说,我需要在自定义元素中调用一个函数,这样当 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/

相关文章:

javascript - 更新 Stockchart y 轴标签更改位置和标签精度

javascript - 表头固定的JS代码TH宽度必须等于TD宽度

javascript - jQuery Sortable 防止用户将子项目移动到父项目

javascript - Mongodb 按 dbref 字段分组

javascript - 覆盖 Foundation 4 Joyride 的默认设置

javascript - 直接设置 Javascript 属性属性而不是 Object.defineProperty

javascript - jQuery:从当前下拉列表之前/之后的选择中选取值

带有自动破折号的 JavaScript

javascript - 如何检查几个元素之一是否存在?

javascript - 浏览器兼容的日期格式