2012-01-26 156 views
0

尝试在单击输入“加号”时添加此表的一行。在按钮上添加行点击

我的HTML

<table name="mytable2" width="100px" border="0" cellspacing="0" cellpadding="0" style="padding-top:5px"> 
    <tr class="st" name="st"> 
    <td width="80px" style="text-align:center; padding-top:3px;"> 
    <input type="Text" id="newst" name="newst" maxlength="25" style="width:80px; font-family:Tahoma; font-size:11px;"></td> 
    <td width="20px"> 
    <input type="submit" name="plus" id="plus" value="+" style="width:20px; text-align:center;"></td> 
    </tr> 
</table> 

我使用的是什么:

<script type="text/javascript"> 
$(document).ready(function() { 
    $("#plus").click(function() { 
$('#mytable2 tbody>tr:last').clone(true).insertAfter('#mytable2 tbody>tr:last'); 
$('#mytable2 tbody>tr:last #st').val(''); 
    $('#mytable2 tbody>tr:last #newst').val(''); 
      $('#mytable2 tbody>tr:last #plus').val('+'); 
return false; 
    }); 
}); 

谁能帮助?

+0

我没有运行你的代码;怎么了? – j08691 2012-01-26 22:35:32

回答

2

ID没有名字:)

<table name="mytable2" 


<table id="mytable2" 

http://jsfiddle.net/brentmn/whgy6/

+0

是的,好的。 – 2012-01-26 22:39:27

+0

... :)谢谢 – 2012-01-26 22:43:21

0

我想也许你得在试图做到这一点的几行代码,并使用框架捆绑...的以下将做你想要的,并且不需要任何库。如果你所担心的字节转移,写清楚代码并用minifier如

http://developer.yahoo.com/yui/compressor/

下面是我工作再压缩它,和它的可读性启动:)

<html> 
<head> 
<title>foo</title> 
<script type="text/javascript"> 
function insertAfter(referenceNode, newNode) { 
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); 
} 

function cloneRow(e) { 

    // first find our row 
    var elem = e; 
    while (elem.tagName != 'TR') { 
    elem = elem.parentNode; 
    } 

    var newElem = elem.cloneNode(true); 
    insertAfter(elem, newElem); 
} 
// ]]> 
</script> 
</head> 
<body> 
<table name="mytable2" width="100px" border="0" cellspacing="0" cellpadding="0" style="padding-top:5px"> 
    <tr class="st" name="st"> 
    <td width="80px" style="text-align:center; padding-top:3px;"> 
    <input type="Text" id="newst" name="newst" maxlength="25" style="width:80px; font-family:Tahoma; font-size:11px;"></td> 
    <td width="20px"> 
    <input type="submit" name="plus" id="plus" value="+" style="width:20px; text-align:center;" onclick="cloneRow(this)"></td> 
    </tr> 
</table> 
</body> 
</html> 

信用其中,信用是因为,你可以看到,我使用了另一种答案插入伎俩这个答案的一部分......

.insertAfter or .append to an Element Id with Javascript. it's a script tag so it can't be with $

请注意,这依赖于在html中传递“this”。如果你用jQuery或其他东西附加它,你需要看看e.target等。