使用委托绑定 jquery 对象时访问它

Access jquery object when binding it using delegates

本文关键字:对象 访问 jquery 绑定      更新时间:2023-09-26

在我之前的帖子中,我希望它找到特定的dom元素。使用解决方案中提供的查找的jquery选择器很棒。但是我想委托这个选择器将其与"上下文菜单"事件绑定。但是如果你在委托中传递 jquery 对象,它将无法工作。我所做的是以下几点。

var slots;
slots = $(".fc-slats > table tbody tr ").find("td:eq(1)");
$(".fc-agenda-view").on("contextmenu", slots, function (e){
    e.preventDefault();
    if (paste===true) {
        showSlotContextualMenu($(this), e);
    }else{
        console.log($(this));
    }
});

我希望$this对象成为插槽,但我读到我不能在"on"中使用jquery对象,但我需要使用选择器。对此的等效选择器是什么?我想要 td 是所需 tr 的第二个孩子。是吗

.fc-slats > table tbody tr td:eq(1)

on 的第二个参数应该是字符串选择器,用于查找主选择器的后代元素。考虑到这一点,这应该有效:

$(".fc-agenda-view").on("contextmenu", '.fc-slats > table tbody tr td:eq(1)', function(e) {
    // your code...
});

这行得通吗?

$(document).on("contextmenu", ".fc-slats > table tbody tr > td:first-child", function (e){
     // .....
});

有效的方法如下。

var selector = ".fc-slats > table tbody tr td:nth-child(2)";
$(".fc-agenda-view").on("contextmenu",selector , function (e){
    e.preventDefault();
    if (paste===true) {
        showSlotContextualMenu($(this), e);
   }else{
        console.log($(this));
   }
});