[英]Dynamically generate HTML control and change the ID attribute with jQuery in ASP.NET Core MVC
我正在 .NET Core MVC 中创建一个订单项表单。 我的表单中有添加按钮。 单击添加按钮表行时,会生成一些 html 控件。 我的表格 html 如下:
<div class="card">
<div class="card-title"><h4>Order Information</h4></div>
<div class="card-body">
<table id="mytable" class="table">
<thead>
<tr>
<th>Item Name</th>
<th>Serial No</th>
<th>Quantity</th>
<th>Unit Price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="extraPerson">
<td>
<select asp-for="OrderDtls[0].ItemName" class="form-control selItem"></select>
</td>
<td>
<input asp-for="OrderDtls[0].SerialNo" type="text" class="form-control" />
</td>
<td>
<input asp-for="OrderDtls[0].Quantity" type="number" class="form-control" />
</td>
<td>
<input asp-for="OrderDtls[0].Price" type="number" class="form-control" />
</td>
<td>
<a href="#" id="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</a>
<a href="#">
<i class="fa fa-minus" aria-hidden="true"></i>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
下面是用于动态创建 html 控件的 jQuery 代码:
$(document).ready(function () {
$("#add").click(function () {
var html = $('#mytable tbody>tr:first').clone(true);
html.find('[class=selItem]').attr("id", "newIds");
html.insertAfter('#mytable tbody>tr:last');
return false;
});
});
现在在这段代码中
html.find('[class=selItem]').attr("id", "newIds");
我想用一个新的 ID 属性更改。 但它没有发生。 谁能给我建议如何做到这一点?
您使用了错误的 class 选择器,从
html.find('[class=selItem]').attr("id", "newIds");
至
html.find(".selItem").attr("id", "newIds");
$(document).ready(function () { $("#add").click(function () { var html = $('#mytable tbody>tr:first').clone(true); html.find(".selItem").attr("id", "newIds"); html.insertAfter('#mytable tbody>tr:last'); return false; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="card"> <div class="card-title"><h4>Order Information</h4></div> <div class="card-body"> <table id="mytable" class="table"> <thead> <tr> <th>Item Name</th> <th>Serial No</th> <th>Quantity</th> <th>Unit Price</th> <th></th> </tr> </thead> <tbody> <tr class="extraPerson"> <td> <select asp-for="OrderDtls[0].ItemName" class="form-control selItem"><option value="Test">Test</option></select> </td> <td> <input asp-for="OrderDtls[0].SerialNo" type="text" class="form-control" /> </td> <td> <input asp-for="OrderDtls[0].Quantity" type="number" class="form-control" /> </td> <td> <input asp-for="OrderDtls[0].Price" type="number" class="form-control" /> </td> <td> <a href="#" id="add">Add <i class="fa fa-plus" aria-hidden="true"></i> </a> <a href="#"> <i class="fa fa-minus" aria-hidden="true"></i> </a> </td> </tr> </tbody> </table> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.