我有跟着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>我需要重复这个html单元,在一个按钮上点击一个增量id作为下面,
当第一次单击时,***-group-x -> ***-group-1
当第二次点击时,***-group-x -> ***-group-2
我试过像咆哮一样,但不起作用,
var html = $('#unit').html();
newhtml = html .replace('group-x', 'group-3'); 任何帮助都会很感激的。
发布于 2014-05-20 08:46:52
使用模板HTML的一个很好的模式是将它隐藏在一个未知类型的脚本块中:
<script id=unit" type="text/template">
<div id="***-group-x">****</div>
</script>这使得维护变得非常容易,因为您所看到的就是您得到的:)
用$('#unit').html()访问它
转换任何替换标记(使用regex,如果替换发生不止一次,因为替换只执行第一次匹配),并在新位置插入:
var html = $('#unit').html().replace('group-x', 'group-' + n);
$('#targetlocationselector').append(html);使用这个号码取决于你的使用。
例如,您可能需要计算已经存在的数量,并在此基础上添加一个:
var n = $('#targetlocationselector').children().length;要在替换中使用regex,可以传递一个RegExp对象而不是字符串,或者使用regex文本(在本例中是合适的):
var html = $('#unit').html().replace(/group-x/g, 'group-' + n);发布于 2014-05-20 08:47:49
您可以在模板中使用正则表达式,比如创建模板。
<div id="element-templates" style="display: none ;">
<div id="::FIELD1::">****</div>
</div>并使用类似的脚本代码。
var jFilesContainer = $("#unit");
var jUploadTemplate = $("#element-templates div:first");
var jUpload = jUploadTemplate.clone();
var strNewHTML = jUpload.html();
var intNewFileCount = (jFilesContainer.find("div").length + 1);
strNewHTML = strNewHTML.replace(new RegExp("::FIELD1::", "i"), intNewFileCount)
jFilesContainer.append(jUpload);发布于 2014-05-20 08:45:52
您可以通过这段代码进行增量,并根据您的需求进行进一步的添加。
var i=0;
$('.unit').each(function(){
i++;
var newID='menu'+i;
$(this).attr('id',newID);
$(this).val(i);
});https://stackoverflow.com/questions/23754885
复制相似问题