Use .bind
when assigning the listener to set a this
value. With jQuery, this
is just the element, or element[i]
.
Since you don't care about the indicies, only the elements, you could also consider iterating over the elements directly:
function $(selector) {
const elements = document.querySelectorAll(selector);
return {
click(callback) {
for (const element of elements) {
element.addEventListener('click', callback.bind(element));
}
}
};
}
$(".entry-content").click(function() {
console.log(this);
});
<button class="entry-content">click</button>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…