何时使用关键字或事件参数?两段jQuery代码的差异与生效原因
Hey there! Let's break down your questions clearly and straightforwardly:
First, let's clarify the roles of these two:
- The event parameter (often named
eventore) is an object the browser automatically passes to your event callback when the event fires. It carries all metadata about the event (like click coordinates, pressed keys) and built-in methods to control how the event behaves. - The
thiskeyword in jQuery event callbacks (when not using arrow functions) points directly to the DOM element that triggered the event. Wrapping it in$()lets you use jQuery's methods to manipulate that element.
Use the event parameter when:
- You need event-specific details: For example, getting the mouse position of a click (
event.clientX,event.clientY), checking which key was pressed in a keyboard event (event.key), or accessing the original element that triggered the event (event.target—useful in event delegation wherethismight refer to a parent element). - You need to modify event behavior: Methods like
event.preventDefault()(stop a link from navigating or a form from submitting),event.stopPropagation()(halt event bubbling up the DOM tree), orevent.stopImmediatePropagation()(block other handlers on the same element from running) only exist on the event object.
Use this (or $(this)) when:
- You just need to manipulate the triggering element: Adding a class (
$(this).addClass('active')), hiding it ($(this).hide()), or updating its content. If your task doesn't involve the event's behavior or metadata,thisis the simpler choice.
Let's first look at the two snippets side by side:
Working Code:
$("span").on("click",function(event){ event.stopPropagation(); })
Non-Working Code:
$("span").on("click",function(event){ $(this).stopPropagation(); })
Key Differences & Why Only One Works:
event.stopPropagation()calls a native method on the event object: This method is part of the browser's Event API, and jQuery passes the standard event object (with minor jQuery enhancements) to your callback. Calling it stops the click event from bubbling up to parent elements—so if the span is inside a div with its own click handler, that div's handler won't run when you click the span.$(this).stopPropagation()tries to call a method that doesn't exist on jQuery objects:$(this)wraps the triggering span into a jQuery object, but jQuery's API doesn't include astopPropagation()method. This line will either do nothing at all or throw a "not a function" error in your browser's console—there's no such method to execute here.
In short: Only the first snippet works because stopPropagation() belongs to the event object, not the DOM element (or its jQuery-wrapped version). You have to call it on the event parameter passed to your callback to get the intended behavior.
内容的提问来源于stack exchange,提问作者siddhant

