gpt4 book ai didi

javascript - 使用 jQuery 更改 HTMLDivElement 中的所有 id

转载 作者:行者123 更新时间:2023-12-03 11:08:34 25 4
gpt4 key购买 nike

我正在使用 jQuery 动态附加 Django 表单集。

我正在使用链接添加另一个与上面的表单相同的表单。我使用以下代码执行此操作:

var row = $("."+class_name).first().clone(true);
row.find('input').val('');
$(row).removeAttr('id').hide().insertAfter("."+class_name).last().slideDown(300);

row[0] 中的每个标签(这是一个 HTMLDivElement)都是 id_cur-0-... 每次我使用这个 jQuery 函数添加一个 div 时,我需要每个 id 来增加 cur 之后的数字。因此,当我第一次单击它时,每个项目都会有 id_cur-1... 下一次他们将有 id_cur-2... 依此类推。

如果我可以将 HTMLDivElement 视为字符串,我可以使用正则表达式来基本上找到每次出现的“cur-\d”。我该怎么做?或者有更好的方法(因为这看起来像是一种黑客)。

这是我的 HTML 的样子:

<div class="item1">
<label style="display:inline-block;" for="id_cur-0-cur_child_name">
Name:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_name" name="cur-0-cur_child_name" type="text" />

<label style="display:inline-block;" for="id_cur-0-cur_child_sex">
Sex:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_sex" name="cur-0-cur_child_sex" type="text" placeholder="[M / F]" />

<label style="display:inline-block;" for="id_cur-0-cur_child_dob">
DOB:
</label>
<input style="display:inline-block;width:10%" class="textinput textInput form-control" id="id_cur-0-cur_child_dob" name="cur-0-cur_child_dob" type="text" placeholder="e.g. 12/25/2014" />
</div>

最佳答案

这样可以吗?

var last_id = $("."+class_name).last().attr("id").split("-")[1];

fiddle

更新

您好,ev.preventDefault 仅用于防止 anchor 的默认行为。它阻止元素的默认操作发生。

我看到了你的 html,这里有一个新的 fiddle

Javascript 代码(已注释):

$("#clone").click(function (ev) {
ev.preventDefault();

var row = $(".item1").last().clone(true);// Last item1
var last_id = $(row).find("input:first").attr("id");// Grab first input id (it contains the important part: the number)
row.find('input').val('');

$.each(row.find('input'), function (index, item) {// Change id of all inputs inside the cloned element.
var id = (+(last_id.split("-")[1])+1), // Grab the number and increase it.
new_id = $(item).attr("id").replace("id_cur-" + last_id.split("-")[1], "id_cur-" + id);// Replace ids with the new number.
$(item).attr("id",new_id);// Asign the new id to the inputs. You'll have to do more or less the same to the labels if you like.
});
$(row).removeAttr('id').hide().insertAfter(".item1:last").slideDown(300);// Insert after the last item1 element. Otherwise it'll insert after all elements with class .item1

});

希望有帮助。

亲切的问候。

关于javascript - 使用 jQuery 更改 HTMLDivElement 中的所有 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27717509/

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