[英]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.