javascript - 创建类来处理元素的点击和其他事件

标签 javascript class events

我想创建类,并希望将我的元素传递给它,并触发事件形成类,而不是每次都从 javascript 事件触发。

我的尝试

HTML:

<div id="upload-container">
<label for="myfile">Select a file:</label>
<input type="file" id="fileInput" name="myfile">
<button id="send"> Upload </button> </div>

Javascript 类:

function Myevents(ele) {
    this.element = ele;
}

Myevents.prototype = {

    init: function() {
        this.element.addEventListener('click', function(file) {
            console.log(file)
        }(this.element));

        this.element.addEventListener('mouseover', function(file) {
            console.log(file)
        }(this.element));
    }
}

var ele = document.getElementById('send');
var instance = new Myevents(ele);
instance.init();

instance.click() ;  // should be able to call it manually
instance.mouseover();   // should be able to call it manually

上面两个调用都没有按要求触发,如何处理这个问题,任何帮助将不胜感激。

最佳答案

在这里,我重新创建了您的 Myevents 函数。我创建了一个点击函数作为原型(prototype),并附加点击事件监听器并隐式调用它。

const Myevents = function(el) {
	this.element = el;
}

Myevents.prototype = {
	click: function() {
    	// Attach the event listener
    	this.element.addEventListener('click', (e) => {
        	e.preventDefault();
            console.log('clicked');
        });
        
        // Finally fire the click
        // this.element.click();
    }
}

const el = document.querySelector('#clickbtn');
const instance = new Myevents(el);
instance.click();
<div>
  <p>Hello World</p>
  <button id="clickbtn">Ok</button>
</div>

注意:我不知道,但如果它满足您的要求,请告诉我。

关于javascript - 创建类来处理元素的点击和其他事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792584/

相关文章:

ios - 如何检测在 Cordova 中按下的主页按钮?

javascript - 我的 JavaScript 使服务器崩溃

javascript - Web Scrape JS 渲染网站

java - 如何使 itemStateChange 方法在按下 JButton 时运行?

c++ - 在一个线程中通过 tcp socket 发送和接收数据

模板类中新结构的 C++ 语法

javascript - 如何在 Electron 中触发自动更新事件以进行测试?

javascript - 将数据解析为 JavaScript 数组

python - 读取 json 时替代 eval

java - 我需要一些帮助来理解实例/引用