获取td的节点索引
如果我有如下所示的主体...我知道如果我单击第一个单选按钮,它会返回 1。如果我单击表格外面的单选按钮,它会返回 2。但是当我单击嵌套表格的第一个 td 时,它会返回它的索引加上两个警报中“父级”的 td 索引。如何仅返回应为 2 的嵌套 td 索引?这只是动态构建的示例表结构,因此它几乎需要与任何表设计和任何 td 配合使用。
有什么建议吗?
这是我用来在用户单击 td 时返回索引的代码(我捕获输入、文本区域等的其他索引):
$("td").click(function (event) {
var nodeIndex = $("td").index();
var nodeName = $(this).get(0).nodeName
alert(nodeName + "," + nodeIndex);
});
这是示例正文:
<body>
<input type="radio" />
<table class="parent_table">
<tr>
<td>
<table class="nested_table">
<tr>
<td>
Sample Text</td>
<td>
</td>
</tr>
</table>
</td>
<td>
</td>
</tr>
</table>
<input type="radio" />
</body>
If I have a body like the following... I know that if I click the first radio it returns 1. If I click the one on the outside of the table it returns 2. But when I click the nested table's first td it returns its index plus the 'parent's td index in two alerts. How can I return the nested td index only which should be 2? This is just a sample table structure that is dynamically built so it needs to work with virtually any table design and any td.
Any suggestions?
This is the code I am using to return the index when a user clicks on a td (I capture other indexes for an input, textarea, etc):
$("td").click(function (event) {
var nodeIndex = $("td").index();
var nodeName = $(this).get(0).nodeName
alert(nodeName + "," + nodeIndex);
});
This is the sample body:
<body>
<input type="radio" />
<table class="parent_table">
<tr>
<td>
<table class="nested_table">
<tr>
<td>
Sample Text</td>
<td>
</td>
</tr>
</table>
</td>
<td>
</td>
</tr>
</table>
<input type="radio" />
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是罪魁祸首,它调用所有
替换为:
This is the culprit, which calls all
<td>
sReplace with:
表已在
td
上具有方便的属性cellIndex
,在tr
上具有rowIndex
。这意味着您不需要使用 jQuery。相反,尝试这样的方法(无论如何,这更有效):
除了更有效之外,它还避免了您在 jQuery 中遇到的混乱。当您单击代码中的嵌套 TD 时,您实际上是在单击父表的 TD 以及嵌套的 TD,因此您会收到两个警报。在这里,你只能得到一个。
Tables already have convenient properties
cellIndex
ontd
, androwIndex
ontr
. This means you do not need to use jQuery.Instead, try something like this (which is more efficient anyway):
On top of being more efficient, it avoids the confusion you're putting jQuery through. When you click on a nested TD in your code, you're actually clicking on the parent table's TD as well as the nested one, so you get two alerts. Here, you'll only ever get one.
解决了。我只是将 td 放入全局单击中,然后能够在一个事件中记录节点名和索引,从而消除了双重警报......
Solved. I just put the td into a global click and then was able to record the nodename and index in the one event which eliminated the double alert....