在方法上的jQuery中获取父选择器

在方法上的jQuery中获取父选择器,jquery,Jquery,是否有办法在该代码的块内获取父选择器(#dataTable tbody)。此处的$(this)返回tr(子选择器) 这里我更愿意做的是不要使用像$(this).最近('dataTable tbody')或类似的方法,它们让我重复父选择器id(#datatabletbody)。只需先将jQuery集合保存在变量中,然后再调用。: const$tbody=$(“#数据表tbody”); $tbody.on(“单击”,“tr”,函数(){ log($tbody.hasClass('tBodyClas

是否有办法在该代码的块内获取父选择器(
#dataTable tbody
)。此处的
$(this)
返回
tr
(子选择器)


这里我更愿意做的是不要使用像
$(this).最近('dataTable tbody')
或类似的方法,它们让我重复父选择器id(
#datatabletbody
)。

只需先将jQuery集合保存在变量中,然后再调用

const$tbody=$(“#数据表tbody”);
$tbody.on(“单击”,“tr”,函数(){
log($tbody.hasClass('tBodyClass');
});

运输署

您可以使用jquery事件对象的delegateTarget属性

$(“#数据表tbody”)。在(“单击”,“tr”,函数(事件){
log($(event.delegateTarget.text());
});

测试1
测试2

$(this).closest('tbody')
或干脆
this.parentElement
resp<代码>$(this).parent()
。无需重复选择器。是否要获取选择器(字符串)或所选元素(jQuery对象/DOM元素)?
$( "#dataTable tbody" ).on( "click", "tr", function() {
    console.log( $( this ).text() );
});