我正在尝试创建一个在表中包含“添加新产品”部分的订单表单。基本上,用户应该能够单击“添加行”链接,并且将出现一个新的输入行,以允许用户将另一个产品添加到订单列表中。我可以完成一次这项工作,但之后表单将不会添加任何新行。在 console.log 中,我可以看到事件处理程序仅作用于原始表单元素,而不作用于新产品输入行。我这里有一个简短的 fiddle :
http://jsfiddle.net/scottm1164/eTBr6/5/
这是我的 jQuery:
<script>
$(document).ready(function () {
(function () {
var start = $('table'),
newRow = $('<tr><td><input type="text" class="quantity" /></td><td><input type="text" class="prodNum" /></td><td><textarea cols="15" rows="1"></textarea></td><td><p class="addRow">Add a Row</p></td></tr>');
$('.addRow').on('click', function () {
$(start).append(newRow);
console.log(this);
});
})(); //end SIAF
}); //END document ready
</script>
这是我的表格:
<form enctype="multipart/form-data" method="post" action="#" id="orderForm">
<ul>
<li>Name:
<br>
<input type="text" id="name" />
</li>
<li>Email:
<br>
<input type="email" id="email" />
</li>
<li>Company:
<br>
<input type="text" id="company" />
</li>
<li>Phone:
<br>
<input type="tel" id="phone" />
</li>
<li>Delivery Address:
<br>
<input type="text" id="delAddress" />
</li>
<li>PO Number:
<br>
<input type="text" id="poNum" />
</li>
<li>If you have a document for your order, attach it here:
<br>
<input type="file" id="docs" />
</li>
<li>
<table id="prodTable" width="auto" border="0" cellpadding="4" cellspacing="4">
<tbody>
<tr>
<td>Quantity</td>
<td>Product Number</td>
<td>Product Description</td>
<td> </td>
</tr>
<tr>
<td>
<input type="text" class="quantity" name="quantity_" />
</td>
<td>
<input type="text" class="prodNum" name="prodNum_" />
</td>
<td>
<textarea cols="15" rows="1" name="prodDesc_"></textarea>
</td>
<td>
<p class="addRow">Add a Row</p>
</td>
</tr>
</tbody>
</table>
</li>
<li>Special Delivery Instructions:
<br>
<textarea cols="30" rows="10" id="instructions"></textarea>
</li>
</ul>
<input type="submit" id="submit" />
</form>
有人可以向我解释一下这段代码出了什么问题吗?我对 jQuery/Javascript 还很陌生,所以我只是不明白为什么该代码只能运行一次,但在后续单击“添加行”后就不起作用了”链接,并且仅在原始“添加行”链接上,但不在新创建的链接上。
最佳答案
试试这个
$('form').on('click', '.addRow', function () {
var start = $('table'),
newRow = $('<tr><td><input type="text" class="quantity" /></td>' +
'<td><input type="text" class="prodNum" /></td>' +
'<td><textarea cols="15" rows="1"></textarea></td>' +
'<td><p class="addRow">Add a Row</p></td></tr>');
$(start).append(newRow);
});
将变量放入点击处理程序中,并通过将表单作为上下文来使用事件委托(delegate)
关于javascript - 允许用户添加表单输入字段: Why is append() only working once?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19434912/