简体   繁体   English

jQuery选择器上的单击事件

[英]JQuery selector on click event

I want to trigger something when I click on a certain class within a div. 当我单击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 : 我的HTML如下: 在此处输入图片说明

The div that you're selecting is the one that has the class .event , not a descendant of it. 您选择的div是具有.event类的类,而不是其后代。 Therefore the correct selector is div.event . 因此,正确的选择器是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: 而且不要忘了,每个选项都应在DOM中就绪,如下所示:

$(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. 您正在使用父级后代选择器,因为event类位于div本身而不是其后代中,所以您的选择器不正确。

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 有关选择正确的选择的更多信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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