我有以下形式克隆形式與jQuery
<div id="div1" style="margin-bottom:4px;" class="clon">
<span id ="display_input1">
Answer:<select name="Answer1" id="Answer1">
<option value='0'>Select Answer</option>
<option value='1'>Excellent</option>
option value='2'>Very Good</option>
</select>
</span>
New Answer<input type="checkbox" id="Enable1" name="Enable1" value="1" onclick=display_inpt(this) />
<?
function dropdown($starting, $factor, $ending)
{
echo "Point<select name=\"Mark1\" id=\"Mark1\">";
echo "<option value=\"\">Select Point</option>";
$i=$starting;
while($i >= $ending)
{
echo "<option value=\"$i\">$i</option>";
$i=$i-$factor;
}
echo "</select>";
}
dropdown(10, .5, -10);
?>
</div>
<input type="button" id="Add" value="Add Another Option" />
我想克隆每次點擊按鈕「添加另一個選項」整個DIV這樣rasult會像
<div id="div2" style="margin-bottom:4px;" class="clon">
<span id ="display_input2">
Answer:<select name="Answer2" id="Answer2">
等等。我用下面的jQuery代碼試圖做到這一點
$(document).ready(function() {
$('#Add').click(function() {
var num = $('.clon').length;
var newNum = new Number(num + 1);
var newElem = $('#div' + num).clone().attr('id', 'div' + newNum);
newElem.children(':eq(0)').attr('id', 'display_input' + newNum);
newElem.children(':eq(1)').attr('id', 'Answer' + newNum).attr('name', 'Answer' + newNum);
newElem.children(':eq(2)').attr('id', 'Enable' + newNum).attr('name', 'Enable' + newNum).attr('value', newNum);
newElem.children(':eq(3)').attr('id', 'Mark' + newNum).attr('name', 'Mark' + newNum);
,但這是不正確的,所以我應該怎麼寫jQuery代碼來實現這一目標?
你有什麼看起來好像沒什麼問題,但你顯然需要實際添加你的'newElem'到DOM(並關閉'click'和'ready'事件處理程序,但我猜你剛剛錯過了這個問題)。爲什麼你使用'新數字'而不是隻增加'num'? – 2011-12-28 09:26:18