我有以下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重新编号文本输入数组索引
发布评论