简体   繁体   中英

jQuery click event handler

I have the below JS code;

var $divContent = $("<div />");
$divContent.on('click.mypop', function(e){
alert(e.type);
}

So there is a div on page with some text content.

My question is there is no element with class "mypop" and still my code goes inside the click handler when I do click action on the div?

How is this possible ?

Please see: jQuery docs . First param is the event type and has nothing to do with anything in the DOM.

You are attaching the handler to event click.mypop . That is just a click event in mypop namespace. You can read more about it in section "Event names and namespaces" here: http://api.jquery.com/on/ In short, namespaces are used to be able to attach and remove specific groups of events without disturbing others.

If you want to attach your handler to elements with mypop class inside the div, you should attach it like this:

var $divContent = $("<div />");
$divContent.on('click', '.mypop', function(e){
    alert(e.type);
}

You're binding the click event incorrecty. Check on the official API documentation on how to use .on() . It should be as follow:

var $divContent = $("<div />");
$divContent.on('click', '.mypop', function(e){
    alert(e.type);
}

There is no event like click.mypop .
Format: $(staticElement).on(event, selector, function) .
Eg: $(document).on('click', '.mypop', function(e){alert(e.type);})

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