我有一个表格,我需要通过点击一个按钮来动态添加行。每行有 3 个文本框和一个清除按钮。单击清除需要清除文本框中的数据,即单击按钮时,我将行的索引发送到一种方法,该方法删除该索引处文本框的内容。
问题 - 添加新行时如何在行按钮的 onClick 属性中指定索引号?
最佳答案
How do i specify the index number in the onClick property of the row button while adding the new row?
你不知道。相反,使用文本框和按钮位于同一行的事实。我可能根本不会在按钮上使用 onclick
;相反,我在 table
上有一个单击处理程序并在那里处理按钮单击(这称为事件委托(delegate))。像这样:
var table = document.getElementById("theTableID");
table.onclick = function(event) {
var elm, row, boxes, index, box;
// Handle IE difference
event = event || window.event;
// Get the element that was actually clicked (again handling
// IE difference)
elm = event.target || event.srcElement;
// Is it my button?
if (elm.name === "clear") {
// Yes, find the row
while (elm && elm !== table) {
if (elm.tagName.toUpperCase() === "TR") {
// Found it
row = elm;
break;
}
elm = elm.parentNode;
}
if (row) {
// Get all input boxes anywhere in the row
boxes = row.getElementsByTagName("input");
for (index = 0; index < boxes.length; ++index) {
box = boxes[index];
if (box.name === "whatever") {
box.value = "";
}
}
}
}
};
...但是如果你想继续使用按钮上的 onclick
属性,你可以捕获它的中间部分:
按钮:
<input type="button" onclick="clearBoxes(this);" ...>
函数:
function clearBoxes(elm) {
var row, boxes, index, box;
// Find the row
while (elm) {
if (elm.tagName.toUpperCase() === "TR") {
// Found it
row = elm;
break;
}
elm = elm.parentNode;
}
if (row) {
// Get all input boxes anywhere in the row
boxes = row.getElementsByTagName("input");
for (index = 0; index < boxes.length; ++index) {
box = boxes[index];
if (box.name === "whatever") {
box.value = "";
}
}
}
}
引用资料:
- > DOM2 Core规范 - 得到所有主要浏览器的良好支持
- > DOM2 HTML规范 - DOM 和 HTML 之间的绑定(bind)
- > DOM3 Core规范 - 一些更新,并非所有主流浏览器都支持
- > HTML5 specification - 现在其中包含 DOM/HTML 绑定(bind),例如
HTMLInputElement
所以你知道value
和name
属性。
题外话:如您所见,我不得不在该代码中显式解决一些浏览器差异并执行一些简单实用的操作(例如找到元素的最近父元素) .如果你使用像 jQuery 这样的不错的 JavaScript 库, Prototype , YUI , Closure , 或 any of several others ,他们会为您做这些事情,让您专注于您的实际问题。
为了给您一个想法,这是第一个用 jQuery 编写的示例(通过事件委托(delegate)处理点击):
$("#theTableID").delegate("input:button[name='clear']", "click", function() {
$(this).closest("tr").find("input:text[name='whatever']").val("");
});
是的,真的。其他图书馆同样会让事情变得更简单。
关于javascript - javascript中的动态索引设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6846668/