【问题标题】:Javascript Looping syntaxJavascript循环语法
【发布时间】:2011-05-09 09:22:37
【问题描述】:

这对某人来说应该很容易,但我似乎无法正确使用语法。我有以下代码,我确信其中 70% 可以用循环来表示:有人可以赐教吗?

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 );
}

【问题讨论】:

  • 什么不行,有什么问题?

标签: javascript loops syntax for-loop


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我会说

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

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

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2011-05-26
      相关资源
      最近更新 更多