gpt4 book ai didi

jquery第n个子问题

转载 作者:行者123 更新时间:2023-12-01 04:54:42 26 4
gpt4 key购买 nike

我研究了其他 jQuery 第 n 个子问题,但似乎没有一个与我遇到的问题相关。

我在 div 中有两个输入,单击提交按钮后将附加这些输入,并且每个新输入都会获得更新的名称和 ID(bandname1、bandname2、bandname3...)。它对于第一个输入(bandname)工作正常,但对于第二个输入(banddescrip)不起作用,我无法弄清楚为什么会这样。

这是适用的代码...

$(document).ready(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first', 'div:nth-child(2)').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled', '');
// business rule: you can only add 5 names
// if (newNum == 5)
//$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function () {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled', '');
// if only one element remains, disable the "remove" button
if (num - 1 == 1) $('#btnDel').attr('disabled', 'disabled');
});
$('#btnDel').attr('disabled', 'disabled');
});

HTML

<div id="input1" class="clonedInput">
<input type="text" name="bandname1" id="bandname1" size="75" value="Band Name" />
<input type="text" name="banddescrip1" id="banddescrip1" size="75" value="Short Description" />
</div>

我也尝试了div input:nth-child(2),但没有成功。

如果我忘记了任何相关信息,请告诉我。

最佳答案

尝试

newElem.children('input[id^="bandname"]').attr('id', 'bandname' + newNum).attr('name', 'bandname' + newNum);
newElem.children('input[id^="banddescrip"]').attr('id', 'banddescrip' + newNum).attr('name', 'banddescrip' + newNum);

注意:id 属性在整个文档中应该是唯一的,在您的情况下,两个元素具有相同的 id,这是无效的

演示:Fiddle

关于jquery第n个子问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15376231/

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