我有这个问题,关于当我按下按钮时它添加了另一个元素加上元素的名称也在数组中递增,有点难以解释但我会提供一些屏幕截图。
我搜索了这个网站,看到了一堆解决方案和诸如此类的东西,不幸的是我似乎无法将其应用到我的问题上。
这是我想要输出的截图。
如果我按下添加按钮,另一个字段集会出现在它上面
结果是
因此,如果我再次按下“添加”按钮,它将显示另一个永无止境的字段集循环以及相应递增的输入类型名称。
代码:
Fielset 布局
<fieldset style="border:1px solid #DSDCDF; padding:10px; margin-bottom:10px;" id="fieldset_fblikeus">
<div class="condition">
<div class="clear"></div>
<div>Label</div>
<div><input class="gate-condition" name="label_" size="30" type="text" value="<?php echo $fb_page[0]; ?>"></div>
<div class="clear" style="padding-top:5px;"></div>
<div>URL to Like</div>
<div><input class="gate-condition" name="url_" size="30" type="text" value="<?php echo $fb_page[1]; ?>"></div>
<div class="clear" style="padding-top:5px;"></div>
</div>
</fieldset>
启动函数的代码
<a onclick="fb_likeus_add();">Add</a>
function fb_likeus_add() {
var fieldset_data = '<fieldset style="border:1px solid #DSDCDF; padding:10px; margin-bottom:10px;"><div class="condition"><div class="clear"></div><div>Label</div><div><input class="gate-condition" name="label_" size="30" type="text" value="<?php echo $fb_page[0]; ?>"></div><div class="clear" style="padding-top:5px;"></div><div>URL to Like</div><div><input class="gate-condition" name="url_" size="30" type="text" value="<?php echo $fb_page[1]; ?>"></div><div class="clear" style="padding-top:5px;"></div></div></fieldset>';
$("#fb_likeus_td").prepend(fieldset_data);
}
主要问题是当我按下添加按钮时如何在将数据添加到 div 的同时增加输入元素的名称,我不知道在哪里/从什么开始。但我已经想到了它应该是什么样子。
Array = [
div1 ['name_1', 'url_1'],
div2 ['name_2', 'url_2'],
div3 ['name_3', 'url_3'],
div4 ['name_4', 'url_4'],
div5 ['name_5', 'url_5']
and so on, it increments when you click the add button.
];
有点难解释,还是希望大家理解我的问题。 如果你们能帮助我,我会很高兴,这意义重大。提前致谢。
最佳答案
对此的一种解决方案是在包含您要插入的标记的页面某处设置一个隐藏的"template"div。在这种特定情况下,标记相对简单,因此您只需将模板标记存储为 JavaScript 字符串即可,但随着时间的推移,这通常比在页面上使用隐藏的 div 更难维护。
无论如何,一旦您有了模板标记,您只需添加少量 JavaScript 代码来跟踪您向页面添加新的 fieldset
的次数。有了它,您可以更新您的 fb_likeus_add()
函数以对模板标记执行简单的字符串替换,在将其添加到 div 之前插入正确的序列号。
这听起来可能有点复杂,但实际上只需要很少的代码:
//initialize this when the page loads
var numAdded = 0;
function fb_likeus_add() {
//increment the counter
numAdded++;
//grab the template html
var templateHtml = $("#template").html();
//write the new count into the template html
templateHtml = templateHtml.replace(/label_/g, "label_" + numAdded)
.replace(/url_/g, "url_" + numAdded);
//prepend the updated HTML to the document
$("#container").prepend(templateHtml);
};
这是一个例子:http://jsfiddle.net/Dw8e7/1/
关于javascript - 按下按钮递增数据然后推送到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14393501/