简体   繁体   中英

JQuery selector on click event

I want to trigger something when I click on a certain class within a div.

I tried this

$("div .event").click(function() {
    alert($( this ).text());
}); 

And

$("div").on("click", $('.event'), function() {
    alert($( this ).text());        
}); 

//Or 
$(".SimpleCalendar .event").click(function() {
    alert($( this ).text());
}); 
//I do not even know what this is supposed to do ...
$(".SimpleCalendar tbody tr td div .event").click(function() {
    alert($( this ).text());
}); 

And many more but still can not figure out why this is not working

My HTML is the following : 在此处输入图片说明

The div that you're selecting is the one that has the class .event , not a descendant of it. Therefore the correct selector is div.event . Try this:

$("div.event").click(function() {
    alert($( this ).text());
});

Or just:

//Warning: if elements unlike the div also have the event class then stick to 
//the above as the selector is more specific
$(".event").click(function() {
    alert($( this ).text());
}); 

And don't forget that each of these options should be in DOM ready like so:

$(function() {
    $("div.event").click(function() {
        alert($( this ).text());
    }); 
});

You were making use of parent descendent selector, since event class is on the div itself and not its descendent your selector was incorrect.

One of these should work for you

Try this

$("div.event").click(function() {
    alert($( this ).text());
});

or,

$(".SimpleCalendar").on("click", '.event', function() {
    alert($( this ).text());        
}); 

For more information on choosing right selectors please see this

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