简体   繁体   中英

Strange behaviour using .on() for click event - Fired twice

I already checked answers about click events fired twice. But I have a question about using .on() .

Usually, I use it like this on dynamically added elements, and it always worked fine:

$(document).on("click", "dynElement", function(){})

In the current website I'm working on, I use it several times. But in the function that I'm trying to achieve, let's say, a dynamic "jump to page", click on page number is triggered twice:

$(document).on("click", ".jumpTo .number", function(){
    console.log("Jump");
}); 

Trying to find the origin of this behaviour, I tried this syntax that works fine:

$(".jumpTo").on("click", ".number", function(){
    console.log("Jump");
});

Can anyone explain what is the difference between these two different syntaxes (which look quite similar to me)?

And optionally , why is $(document).on("click", ".jumpTo .number", function(){}) triggered twice? (Optionally because I am not able to reproduce this behaviour in a Fiddle , everything works as it is supposed to).

$(document).on("click", ".jumpTo .number", function(){
    console.log("Jump");
}); 

In this case the click handler is set on the document object. So whenever you click somewhere on the page, it will fire and look for a ".jumpTo .number" element inside it. If it finds it, it will check if the click was on it and your function will execute.

$(".jumpTo").on("click", ".number", function(){
    console.log("Jump");
});

Here the click handler will be on .jumpTo

As Al.G said probably this code gets executed multiple times, so you actually add that handler multiple times, hence the double firing. One way to solve it is to do something like this:

$(".jumpTo").unbind("click").on("click"...

Another is to change your code to make sure the .on() call doesn't get executed twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM