javascript - 点击事件上的 JQuery 选择器

标签 javascript jquery

我想在点击 div 中的某个类时触发某些内容。

我试过了

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

还有

$("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());
}); 

还有更多,但仍然无法弄清楚为什么这不起作用

我的 HTML 如下: enter image description here

最佳答案

您选择的 div 具有类 .event,而不是它的后代。因此,正确的选择器是div.event。试试这个:

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

或者只是:

//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());
}); 

并且不要忘记每个选项都应该在 DOM 中准备好,如下所示:

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

关于javascript - 点击事件上的 JQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32655277/

相关文章:

带有分号插入的 Javascript 缩小

javascript - 如何让我的移动 div 通过按下按钮来移动,而不是通过按下 div 本身来移动?

javascript - 缩放后获取 "visible"视口(viewport)区域

jquery - 填充 Kendo Read 数据源

javascript - 推迟 JavaScript 解析不起作用

javascript - 离开 slider 后如何重新启动自动播放音频/视频

javascript - 克隆带有所有嵌套元素的 div 以及纯 javascript 中的事件

javascript 替换 匹配 str.replace(/%|\$\s?|(,*)/g, '' ) 中的 % 但不匹配 str.replace(/\$\s?|(,*)|%/g, '')

javascript - Rails 3. 如何使用 jQuery 向订单项添加税费?

javascript - 全页导航幻灯片淡入淡出问题