gpt4 book ai didi

javascript - 如何将具有修改 (id) 内容的内联模板元素附加到另一个元素?

转载 作者:行者123 更新时间:2023-11-30 15:32:13 25 4
gpt4 key购买 nike

在下面的示例中,我希望每次单击添加按钮时获取 template div 内的元素并将其附加到 landingzone class 元素。但与此同时,我需要 NEWID 来更改新元素。当然这只是一个例子,表格的东西可以是 div 或其他任何东西。

形式:

<form method="post">
<input type="text" name="title">
<input type="text" name="number">
<table>
<thead>
<tr> <th>Parts</th> </tr>
</thead>
<tbody class="landingzone">
</tbody>
</table>
<input type="submit" value="Save">
<input type="button" name"add" class="add" value="Save">
</form>

模板:

<div class="template" style="display: hidden">
<tr id="NEWID">
<td>
<input type="text" name="part_NEWID">
</td>
</tr>
</div>

实现此目标的最佳方法是什么?

最佳答案

这是您需要的示例。 javascript 将在不更改任何 html 的情况下工作,除了 name"add" 应该是 name="add"

我在这里所做的是获取 template tr 的 ID 并使用 increment 和 input 字段名称对其进行设置。

var $landingzone = $('.landingzone');
var $add = $('.add');
var desiredId = 'id';
$add.on('click', function() {
var $template = $('.template').find('tr');
var id = $template.attr('id');
var idArr = id.split('-');
if (!idArr[1]) {
id = desiredId + '-1';
} else {
id = desiredId + '-' + (parseInt(idArr[1]) + 1);
}
$template.attr('id', id);
$template.find('input').attr('name', 'part_'+id);
console.log('input id--->'+id, 'input name--->'+'part_'+id);
$landingzone.append($template.clone());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="title">
<input type="text" name="number">
<table>
<thead>
<tr>
<th>Parts</th>
</tr>
</thead>
<tbody class="landingzone">
</tbody>
</table>
<input type="submit" value="Save">
<input type="button" name="add" class="add" value="Add">
</form>

<table class="template" style="display: none">
<tr id="NEWID">
<td>
<input type="text" name="part_NEWID">
</td>
</tr>
</table>

关于javascript - 如何将具有修改 (id) 内容的内联模板元素附加到另一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42064085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com