2012-01-26 225 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等。