我有以下 html 单元。
<div id="unit">
<div id="***-group-x">****</div>
<div id="***-group-x">****</div>
<div id="***-group-x">****</div>
<input type="hidden" id="***-group-x" />
</div>
我需要在按钮单击时使用增量 ID 重复此 html 单元,如下所示,
第一次点击时,
***-group-x
-> ***-group-1
当第二次点击时,
***-group-x
-> ***-group-2
我尝试了如下方法,但没有成功,
var html = $('#unit').html();
newhtml = html .replace('group-x', 'group-3');
如有任何帮助,我们将不胜感激。
最佳答案
使用模板化 HTML 的一个很好的模式是将其隐藏在未知类型的脚本 block 中:
<script id=unit" type="text/template">
<div id="***-group-x">****</div>
</script>
这使得维护变得非常容易,因为所见即所得:)
使用$('#unit').html()
访问它
转换任何替换标记(使用正则表达式,如果它们出现多次,因为替换仅匹配第一个匹配项)并插入新位置:
var html = $('#unit').html().replace('group-x', 'group-' + n);
$('#targetlocationselector').append(html);
管理号码取决于您的使用情况。
例如您可能需要计算已存在的数量并加一:
var n = $('#targetlocationselector').children().length;
要在替换中使用正则表达式,您可以传递 RegExp 对象而不是字符串,或者使用正则表达式文字(适合本例):
var html = $('#unit').html().replace(/group-x/g, 'group-' + n);
关于jquery - 使用增量 id 重复 html 单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23754885/