gpt4 book ai didi

Javascript 添加行到 HTML 表和增量 ID

转载 作者:太空狗 更新时间:2023-10-29 15:11:07 24 4
gpt4 key购买 nike

这是我在这个网站上的第一篇文章,所以希望你能对我宽容一些。我正在尝试创建一个 HTML/PHP 表单并使用一小段 Javascript 在单击按钮时向表中添加其他行并增加两个字段的 ID。

该按钮用于添加行,但它似乎不会增加 ID,只需使用与前一行相同的 ID。希望有人能提供帮助?

$(window).load(function(){
var table = $('#productanddates')[0];

var newIDSuffix = 2;
$(table).delegate('#button2', 'click', function () {
var thisRow = $(this).closest('tr')[0];

var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});

cloned.insertAfter(thisRow).find('input:date').val('');

newIDSuffix++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="blue-bar ta-l">
<div class="container">
<h1>Submit Your Insurance Renewal Date(s)</h1>
</div>
</div>
<div class="grey-bar">
<div class="container">
<div class="rounded-box">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" autocomplete="off" required />
</div>
<div>
<label for="name">Renewal Dates</label>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="5" id="productanddates" class="border">
<tr>
<td>
<select name="insurance_type1" id="insurance_type1">
<option></option>
<option>Car</option>
<option>Home</option>
<option>Van</option>
<option>Business</option>
<option>GAP</option>
<option>Travel</option>
</select>
</td>
<td>
<input type="date" name="renewal_date1" id="renewal_date1" />
</td>
<td>
<input type="button" name="button2" id="button2" value="+" />
</td>
</tr>
</table>
<div>
<label for="telephone_number">Contact Number</label>
<input type="tel" id="telephone_number" name="telephone_number" pattern="\d{11}" autocomplete="off" required />
</div>
<div>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" autocomplete="off" required />
</div>
<div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</div>

最佳答案

cloned.insertAfter(thisRow).find('input:date').val('');

此行不正确。它将抛出一个 invalid selector 错误。

您需要将其更改为:

cloned.insertAfter(thisRow).find('input[type="date"]').val('');

jQuery 实际上支持选择器中的 :INPUT-TYPE 格式,但不支持新的 HTML5 输入类型(目前):所以使用 input[type="date"] 这是目前选择 HTML5 类型元素的正确方法。请注意值周围的引号。如果要选择具有特定值的属性。

这里是 css 选择器的选择器概述:W3schools .

因为该行抛出错误,所以您的 newIDSuffix 永远不会更新,因为脚本因脚本错误而暂停在该行之前。


@ Charlietfl提出了关于更多地了解类和 DOM 遍历的有效观点。但是,这不会修复此代码。或者解释为什么您的代码不起作用。尽管如此,这是一个很好的提示。

关于Javascript 添加行到 HTML 表和增量 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28970304/

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