Home > Web Front-end > JS Tutorial > body text

Detailed explanation of common errors in dynamically adding click events in js

一个新手
Release: 2017-09-20 09:25:52
Original
2384 people have browsed it

In the front-end, we often add click events. Especially adding click events to dynamic elements. Often there will be no response after adding it.
Possible reasons:

  1. The name of the click event is written incorrectly
    This low-level mistake is often made. The event added in the js code is actually Nothing has been added. The names of the two are different or there is a problem with the selector and the element is not selected.
    For this problem, you can select the element in the debugging window and check whether a listening event has been added.
    As shown in the figure:
    Detailed explanation of common errors in dynamically adding click events in js
    The click event has been added, if not. Then check your variable names and selectors.


  2. In the debugging, the click event was obviously added, but there was no response
    I encountered this problem today. There are two possibilities for this problem.

    ① There is another event that has the opposite function and is also executed. This is the bubbling of the event. All there is no response, in fact the event is executed. Breakpoints can also be entered into breakpoints. Then there are two ways to solve the problem

One is to return false directly to prevent the event from bubbling and also prevent the behavior The code is as follows

$("selector").on('click',function(){
            return false;
        });
Copy after login

The second is to use event.stopPropagation to organize bubbling. This will only prevent the bubbling of events, but will not prevent the bubbling of behaviors. The code is as follows

$("selector").on('click',function(){
             event.stopPropagation();
        });
Copy after login

② For layout issues, click Event added. But this element was not clicked, so the time was not triggered. The possible reason is that after positioning this element, a z-index attribute is set to a negative value, so this element is not clicked. Just change this attribute

The above is the detailed content of Detailed explanation of common errors in dynamically adding click events in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!