Home >Web Front-end >JS Tutorial >Js bubbling event prevention code_javascript skills
1. Event target
Now, the variable event in the event handler holds the event object. The event.target attribute stores the target element where the event occurred. This attribute is specified in the DOM API, but is not implemented by all browsers. jQuery makes the necessary extensions to this event object so that this property can be used in any browser. With .target, you can determine the element in the DOM that first received the event (i.e. the element that was actually clicked). Moreover, we know that this refers to the DOM element that handles the event, so we can write the following code:
2. Stop event propagation
The event object also provides a .stopPropagation() method, which can completely prevent the event from bubbling. Like .target, this method is a pure JavaScript feature, but cannot be used safely in a cross-browser environment. However, as long as we register all event handlers through jQuery, we can safely use this method.
Next, we will delete the check statement event.target == this we just added and add some code in the button's click handler:
As before, you need to add a parameter to the function used as the click handler in order to access the event object. You can then prevent all other DOM elements from responding to this event by simply calling event.stopPropagation(). In this way, the button click event will be handled by the button, and only the button. Clicking elsewhere on the style converter collapses and expands the entire area.
3. Default operation
If we register the click event handler to an anchor element instead of an outer
Supplement:
//Click the outer div of the button to trigger the event (hidden button)
$(document).ready(function() {
$('#switcher').click(function() {
$('#switcher .button').toggleClass('hidden');
});
});
This can also be done by modifying the behavior of the button to achieve the goal.
Prevent event bubbling with JS
Event bubbling: When an event is triggered on an element, such as the mouse clicking a button, the same event will be triggered in all ancestor elements of that element. This process is called event bubbling; the event bubbles up from the original element to the top of the DOM tree.
You can use JS to prevent js events from bubbling. Because of the differences in browsers, the JS writing methods of IE and FF are slightly different.
IE uses cancelBubble=true to prevent it, while FF needs to use the stopPropagation method.
The next complete code:
点击aaaa会触发上层的onclick事件,点击bbbb不会触发上层onclick事件
aaaa | bbbbb |