2011-05-09 42 views
0

这对于某人来说应该很容易,我似乎无法得到正确的语法。我有以下代码,我相信70%的代码可以用循环表示:请有人给我启发一下吗?Javascript循环语法

function AddNewEmail(){ 
var jFilesContainer = $("#emails"); 
var jUploadTemplate = $("#email-templates div.template"); 
var jUpload = jUploadTemplate.clone(); 
var strNewHTML = jUpload.html(); 
var intNewFileCount = (jFilesContainer.find("div.template").length + 1); 
jUpload.attr("id", ("emailedit[" + intNewFileCount + "]")); 
strNewHTML = strNewHTML 
    .replace(
     new RegExp("::FIELD1::", "i"), 
     intNewFileCount 
     ) 
      .replace(
     new RegExp("::FIELD2::", "i"), 
     intNewFileCount 
     ) 
      .replace(
     new RegExp("::FIELD3::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD4::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD5::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD6::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD7::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD8::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD9::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD10::", "i"), 
     intNewFileCount 
     ) 
       .replace(
     new RegExp("::FIELD11::", "i"), 
     intNewFileCount 
     ) 
      .replace(
     new RegExp("::FIELD12::", "i"), 
     intNewFileCount 
     ) 

; 

jUpload.html(strNewHTML); 
jFilesContainer.append(jUpload); 
} 
+0

什么不行,问题是什么? – 2011-05-09 09:25:12

回答

2

如果您使用正则表达式,使用它们:

strNewHTML = strNewHTML.replace(/::FIELD\d{1,2}::/gi, intNewFileCount); 
+0

+1,我在想什么... – 2011-05-09 09:29:48

+1

你忘了'g'修饰符...有时我讨厌JS。 .. – 2011-05-09 09:33:11

+0

这与g修饰符工程是一个治疗 - 更清洁的代码! – Neokoenig 2011-05-09 09:38:59

2

我想说

strNewHTML = strNewHTML.replace(/::FIELD\d+::/gi, intNewFileCount); 

可以代替您的整个strNewHTML逻辑。不是一个循环,但更短。