我想创建类,并希望将我的元素传递给它,并触发事件形成类,而不是每次都从 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/