我有一个表,我需要点击一个按钮动态添加行。每行有3个文本框和一个清除按钮。点击清除时,需要清除文本框中的数据,即点击按钮时,我将该行的索引发送到删除该索引处文本框内容的方法。在javascript中的动态索引设置
问题 - 如何在添加新行时在行按钮的onClick属性中指定索引号?
我有一个表,我需要点击一个按钮动态添加行。每行有3个文本框和一个清除按钮。点击清除时,需要清除文本框中的数据,即点击按钮时,我将该行的索引发送到删除该索引处文本框内容的方法。在javascript中的动态索引设置
问题 - 如何在添加新行时在行按钮的onClick属性中指定索引号?
最好使用事件代理,或者您可以在JavaScript中使用this
。
事件代理瓦特/ jQuery的
<input class="clear-row-btn" type="button" >Clear Row</input>
.live事件
$(".clear-row-btn").live("click", function(){
var $tr = $(this).closest("tr");
$tr.find("input[type='text']").val("");
});
HTML瓦特/的onclick方法
<input type="button" onclick="clearRow(this)" >Clear Row</input>
jQuery的
function clearRow(btn) {
var $tr = $(btn).closest("tr");
$tr.find("input[type='text']").val("");
}
的JavaScript
function clearRow(element) {
while(element.nodeName!='TR'){
element = element.parentNode;
}
//find textboxes inside the element, which is now the parent <tr>
}
我如何从btn获得父母TR? –
如何指定在该行按钮的onclick属性的索引数量,同时增加新的行?
你不知道。相反,请使用文本框和按钮位于同一行的事实。我可能根本不会在按钮上使用onclick
;相反,我会在table
上有一个单击处理程序,并在那里处理按钮单击(这称为事件委托)。事情是这样的:
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 = "";
}
}
}
}
参考文献:
HTMLInputElement
,所以你知道value
和name
属性。题外话:正如你所看到的,我已经解决了一些浏览器的差异,做一些简单实用的东西(比如寻找一个元素的最近的父元素)明确地在码。如果您使用像jQuery,Prototype,YUI,Closure或any of several others这样的像样的JavaScript库,他们会为您做这些事情,让您专注于自己的实际问题。
为了给你一个想法,这里是用jQuery写了第一个例子中(通过处理事件委派点击):
$("#theTableID").delegate("input:button[name='clear']", "click", function() {
$(this).closest("tr").find("input:text[name='whatever']").val("");
});
是的,真的。其他图书馆也会使事情变得更简单。
一个非常好的答案! –
谢谢..上面提供的clearBoxes方法为我完成了这项工作。 –
@Sanman:很好,这很有帮助。不要忘记接受答案,以便您的问题被标记为“已回答”。详情:* [如何接受答案工作?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)* –
请注意 - 我们也有使用Jquery的灵活性,因此使用它的一些方法也会有所帮助。 –
@Sanman:我刚刚给我的答案添加了一个使用jQuery的示例。我之前没有看到您的评论,但它恰好是我在我的示例中使用的库,它有多少库可以为您节省麻烦。 :-) –