JQuery 如何在 onclick 函数中获取嵌套的 id

JQuery how to get nested id inside onclick function

<button class="button" onclick="$('#4').popover('show')">Click me</button>

我有一些类似上面代码片段的代码。我只需要一个 id 来传递到 onclick 事件。

我想用的实际id是这个按钮sibling的id,我可以通过

$(this).prev().attr('id')

我想知道如何用#$(this).prev().attr('id') 替换#4。有什么想法吗?

你可以试试 .parent() 像这样:

$(this).parent('#parentId')

...如果是父级,或者他们处于同一级别?

当然,您可以编写一些脚本,在其中为该父 ID 创建变量,这样您就可以编写:

var parentID = $(this).parent('#parentId');

那么你可以这样写:

$(parentID).popover('show')

对于兄弟姐妹,您可以使用:

$(this).siblings( "#siblingId" )

谢谢人造丝!我得到了答案 - 超级简单!

$(this).prev().popover('show')