我下面有一个嵌套循环表,我想访问 <td>
内的元素元素是 <div>
名为 divrep
的元素目前已关闭。
我想访问这个div
当输入按钮名为 Reply
时的元素单击以便我可以打开它。我在下面有一个 JavaScript 代码来打开它,但它总是会打开第一行。
如何根据单击的输入按钮所在的索引在表格行的精确索引中打开它?到目前为止,这就是我所拥有的:
function OpenReply() {
var div = document.getElementById("divrep");
div.style.display = "block";
}
<table id="mytable">
@foreach (var item in Model.Comments )
{
<tr >
<td class="tdstyle" >
<div > @Html.DisplayFor(modelItem => item.name) </div>
<p> @Html.DisplayFor(modelItem => item.comment) </p>
<p> <input type="button" id="Reply" name="Reply" value="Replie(s)" onclick ="return OpenReply()" /> </p>
<div id="divrep" style="display:none>
<table>
@foreach (var item2 in Model.Replies.Where(r => r.idrep == item.Id))
{
<tr >
<td >
<div> @Html.DisplayFor(modelItem => item2.namerep) </div>
<p >@Html.DisplayFor(modelItem=>item2.reply) </p>
</td>
</tr>
}
</table>
@using (Html.BeginForm("PostComment", "Profile", FormMethod.Post, new { }))
{
<div class="editor-field" style="display:none; margin-bottom:5px;margin-top:5px">
<input type="text" id="comidvalue" name="idrep" value="@Html.DisplayFor(modelItem=>item.Id)" />
<span class="field-validation-valid" data-valmsg-for="idrep" data-valmsg-replace="true"></span>
</div>
<br />
<input type="text" id="namerep" name="namerep" />
<span class="field-validation-valid" data-valmsg-for="namerep" data-valmsg-replace="true"></span>
<br />
<textarea id="reply" name="reply" style="width:445px;height:100px;resize:none" ></textarea>
<span class="field-validation-valid" data-valmsg-for="reply" data-valmsg-replace="true"></span>
<input type="submit" value="Post Reply" name="butname" />
}
<br />
</div>
</td>
</tr>
}
</table>
最佳答案
您不得对同一 html 文档中的多个元素使用相同的 id
。使用class
代替id,如下所示
<input type="button" class="Reply" name="Reply" value="Replie(s)" onclick ="return OpenReply()" />
<div class="divrep" style="display:none>
.....
使用下面的 jQuery 来显示按钮的 divrep
div onclick
$(function(){
$('.Reply').click(function(){
$(this).closest('p').next('.divrep').show();
});
});
<强> DEMO
关于javascript - 如何访问正在循环的表的 <td> 元素内的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26137984/