作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<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/
我是一名优秀的程序员,十分优秀!