[英]How to get the Exact Parent Item With Class Name In JavaScript?
<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>
The IDs of checkbox are automatically generating with my some code. 我的一些代码会自动生成复选框的ID。 Plus there is a loop on the DIV with Class Name "wrapped".
另外,DIV上有一个循环,其类名为“ wrapped”。 This whole Code prints for least 2 times.
整个代码至少打印两次。 And seems like that
看起来像那样
<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>
Now I am trying to add some JS which help me to get the div with class 'Wrapped'. 现在,我尝试添加一些JS来帮助我获得“包装”类的div。 Here is my js
这是我的js
function myFunction(el) {
var el = document.getElementById(el);
var r1 = el.closest(".wrapped");
alert (r1.innerHTML);
}
It always returns me the HTML of the First div with class 'Wrapped'. 它总是向我返回“包装”类的First div的HTML。 What I want is that if i click checkbox with ID val2 it should return me the second div with class 'Wrapped'.
我想要的是,如果我单击ID为val2的复选框,它将返回第二个带有“包装”类的div。 But in all my struggle around the net I am only getting first in all options.
但是,在我所有围绕网络的斗争中,我只获得所有选择的第一。 Thanks In advance
提前致谢
But it is correct and returns desired .wrapped
div. 但这是正确的并返回所需的
.wrapped
div。
Also you can pass the .wrapped
directly to your function: 您也可以将
.wrapped
直接传递给函数:
onclick="myFunction(this.closest('.wrapped'))"
And js: 和js:
function myFunction(wr) {
alert (wr.innerHTML);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.