用jQuery重新编号文本输入数组索引

编程入门 行业动态 更新时间:2024-10-28 21:15:21
本文介绍了用jQuery重新编号文本输入数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下HTML块,用于作为表单的一部分从用户收集有关某项的信息:​​

I have the following block of HTML which is used to collect information about an item from the user as part of a form:

<div class="clone_block"> Name: <input type="text" name="items[0][name]" /><br /> Amount: <input type="text" name="items[0][amount]" /><br /> <button class="delete">Delete</button> </div>

我可以克隆此元素(如果用户要添加其他项目),并将其放置在DOM中div.clone_block的最后一个实例之后,一切正常,我还可以删除元素.但是,我最终得到了多个具有相同名称的文本输入实例,这意味着在POST请求中仅显示最后一个(覆盖了前一个).我要做的是重新编号所有项目,以便第一个是item[0],第二个是item[1]等.

I can clone this element (if the user wants to add another item) and place it after the last instance of div.clone_block in the DOM and everything works fine, and I can also delete elements. However, I end up with multiple instances of text inputs with the same name, which means only the last one shows up in a POST request (the previous ones are overwritten). What I want to do is re-number all the items so that the first is item[0], the second is item[1] etc.

有没有办法在jQuery中做到这一点?以这种方式创建名称使使用PHP处理POST数据更加容易,因此我不想更改命名方案.

Is there a way to do this in jQuery? Creating the names in this way makes it easier to process the POST data with PHP, so I don't want to change the naming scheme if possible.

推荐答案

您可以实现类似的操作,以便在每次克隆/删除后重命名元素:

You can implement something like this to rename the elements after each clone/removal:

function renumber_blocks() { $(".clone_block").each(function(index) { var prefix = "items[" + index + "]"; $(this).find("input").each(function() { this.name = this.name.replace(/items\[\d+\]/, prefix); }); }); }

演示: jsfiddle/Wzzf2/1/

更多推荐

用jQuery重新编号文本输入数组索引

本文发布于:2023-10-23 19:29:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521800.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   文本   编号   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!