如何用原生JavaScript替代jQuery实现元素事件监听绑定?
Got it! Let's walk through converting your jQuery code to plain JavaScript, step by step. First, let's recap what your original code does: it selects all elements with the .my-class class, removes any existing event listeners on them, then binds mouseenter, mouseleave, and click events while preserving the correct this context.
Step 1: Select Target Elements
Instead of jQuery's this.$('.my-class'), use document.querySelectorAll('.my-class') to grab all matching elements. This returns a NodeList, which we can loop through with forEach.
Step 2: Prepare Bound Handlers
jQuery's .bind(this) makes sure your event handlers use the right this context. In vanilla JS, we’ll pre-bind our handlers once (instead of binding inside the loop, which creates a new function every time) — this is crucial because removeEventListener requires the exact same function reference to work properly.
Step 3: Clean Up Old Listeners & Bind New Ones
jQuery’s .off() clears existing listeners for the events we’re targeting. In vanilla JS, we need to explicitly remove each listener using our pre-bound references, then attach the new ones.
Here’s the full vanilla JS equivalent:
// Get all elements with the .my-class selector const elements = document.querySelectorAll('.my-class'); // Pre-bind handlers to keep the correct `this` context const boundMouseEnter = this.handleMouseOverEvent.bind(this); const boundMouseLeave = this.handelMouseLeaveEvent.bind(this); const boundClick = this.handelMouseLeaveEvent.bind(this); // Loop through each element to manage event listeners elements.forEach(element => { // Remove existing listeners first (matches jQuery's .off()) element.removeEventListener('mouseenter', boundMouseEnter); element.removeEventListener('mouseleave', boundMouseLeave); element.removeEventListener('click', boundClick); // Attach the new event listeners element.addEventListener('mouseenter', boundMouseEnter); element.addEventListener('mouseleave', boundMouseLeave); element.addEventListener('click', boundClick); });
Quick Heads-Up
I noticed a typo in your original code: handelMouseLeaveEvent should probably be handleMouseLeaveEvent (missing a 'd'). I kept the typo in the example to match your code, but fixing that will prevent unexpected runtime errors!
内容的提问来源于stack exchange,提问作者Mari Selvan

