需要获取当前元素的id

need to get id of current element

本文关键字:元素 id 获取      更新时间:2023-09-26

因此,我使用基于类的jQuery迭代了几个表,但我的行为需要根据我所在元素的id略有改变

<table id="Brokers" class="nodeTable" border=1 />
<table id="Controllers" class="nodeTable" border=1 />
<table id="Cluster-Drivers"  class="nodeTable" border=1 />
jQuery(".nodeTable").html(nodeHealthTable({
  Role: jQuery(this).attr("id")
}))

这最终会用空字符串填充Role。如何访问当前元素的id?

this在您的代码中没有引用所选元素,html方法接受一个函数,在该函数的上下文中this引用当前元素(jQuery内部使用each方法)。

jQuery(".nodeTable").html(function() {
    return nodeHealthTable({ Role: this.id });
})