Replace()仅适用于一种代码配置

时间:2014-02-12 18:30:55

标签: javascript jquery

我有一段代码复制<table>,但在此过程中更改了ID。这需要几个小时,但我最终还是得到了这个:

var lookFor = 'url' + parseInt(uploadCount);
++uploadCount; //used to create a unique id
var replaceWith = 'url'+parseInt(uploadCount);
var regex = new RegExp(lookFor, 'g');
var tableHTML = '<table class="user-url-table" style="opacity:0;" id="url' + uploadCount + '">' + $('table.user-url-table').first().html().replace(regex, replaceWith) + '</table>';
$(tableHTML).insertAfter($('table.user-url-table').last());

但是,以下情况不起作用:

var lookFor = 'url' + parseInt(uploadCount);
var tableHTML = '<table class="user-url-table" style="opacity:0;" id="url' + uploadCount + '">' + $('table.user-url-table').first().html() + '</table>';
++uploadCount;
var replaceWith = 'url'+parseInt(uploadCount);
var regex = new RegExp(lookFor, 'g');
tableHTML = $('table.user-url-table').first().html().replace(regex, replaceWith);

但他们不应该做同样的工作....第一段代码肯定只是在一行中完成所有操作,而第二段则构成<table>,然后更改其中所有id的实例。

1 个答案:

答案 0 :(得分:1)

第二个代码有两个错误。首先,当你在最后一行做tableHTML = $('table.user-url-table').first().html().replace(regex, replaceWith);时,你会抛弃你所做的准备。您覆盖tableHTML

的值

第二个错误是结果未附加到文档中,就像您在第一个代码中使用insertAfter一样。

要使其工作,请将最后一行替换为$('table.user-url-table').after(tableHTML.replace(regex, replaceWith));。这将插入tableHTML,替换的id为after第一个表。

另一种更简单的做同样事情的方法是:

var firstTable = $("#url1 tbody").html();
var result = "";
for (i = 2; i < 10; i++) {
    result += '<table class="user-url-table" style="opacity:0.2;" id="url'
              + i + '">' + firstTable.replace("url1", "url" + i) + '</table>';
}
$("#url1").after(result);

小提琴:http://jsfiddle.net/bortao/ydEPr/