gpt4 book ai didi

javascript - 如何在 JavaScript 中获取具有类名的精确父项?

转载 作者:行者123 更新时间:2023-12-03 01:13:19 26 4
gpt4 key购买 nike

<div class="wrapped">

<table id="tabled">
<tr>
<td>abc</td>
<td>def</td>
<td><input type="checkbox" class="chkbox" id="val" onclick="myFunction(this.id)"></input></td>
</tr>
<tr>
<td>abc</td>
<td>def</td>
<td><input type="checkbox" class="chkbox" id="val1" onclick="myFunction(this.id)"></input></td>
</tr>

</table>

</div>

复选框的 ID 是用我的一些代码自动生成的。另外,DIV 上有一个类名“wrapped”的循环。整个代码至少打印 2 次。看起来是这样的

<div class="wrapped">
<table id="tabled">
<tr>
<td>abc</td>
<td>def</td>
<td><input type="checkbox" class="chkbox" id="val1" onclick="myFunction(this.id)"></input></td>
</tr>
</table>
</div>

<div class="wrapped">
<table id="tabled">
<tr>
<td>abc</td>
<td>def</td>
<td><input type="checkbox" class="chkbox" id="val2" onclick="myFunction(this.id)"></input></td>
</tr>
</table>
</div>

现在我尝试添加一些 JS 来帮助我获取带有“Wrapped”类的 div。这是我的js

function myFunction(el) {
var el = document.getElementById(el);
var r1 = el.closest(".wrapped");
alert (r1.innerHTML);
}

它总是返回带有“Wrapped”类的第一个 div 的 HTML。我想要的是,如果我单击 ID 为 val2 的复选框,它应该返回第二个带有“Wrapped”类的 div。但在我在网上的所有挣扎中,我只是在所有选择中获得了第一。提前致谢

最佳答案

但它是正确的,并返回所需的 .wrapped div。

您还可以将 .wrapped 直接传递给您的函数:

 onclick="myFunction(this.closest('.wrapped'))"

还有 js:

function myFunction(wr) {
alert (wr.innerHTML);
}

关于javascript - 如何在 JavaScript 中获取具有类名的精确父项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52128108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com