2015-06-03 126 views
0

我有下面的代码循环的一部分的DOM,搜索3个不同的字符串,并用其他东西替换每个。我需要做到这一点,以便任意数量的项目可以被搜索和替换,而不是只有3。这是可能的jQuery?

function getDomArray(domClone){ 
    var postRows = []; 

    $(domClone).each(function() { 
     var find1 = "__hidden__"; 
     var find2 = "__bigtext__"; 
     var find3 = "col-sm-12"; 
     var re1 = new RegExp(find1, "g"); 
     var re2 = new RegExp(find2, "g"); 
     var re3 = new RegExp(find3, "g"); 

     $(this).html(function (index, html) { 
      return html.replace(re1, '').replace(re2, 'bigtext').replace(re3, "col-sm-4"); 
     }); 
     postRows.push($($(this).html()).encodeHtml()); 
    }); 

    return postRows; 
} 

更新1:在@ JonathanCard的答案代码引发此错误:

Cannot read property 'replace' of undefined

请参见本文的jsfiddle:http://jsfiddle.net/jsFiddlePlayer/vhg7csb7/12/

更新2:在回答作品的代码!

回答

2

试试这个:

function getDomArray(domClone) { var postRows = []; 
    list_to_replace = {"__hidden__": '', "__bigtext__": "bigtext", "col-sm-12": "col-sm-14"}; 
    $(domClone).each(function() { 
     $.each(Object.keys(list_to_replace), function(index, item) { 
      var re = new RegExp(item, "g"); 
      $(domClone).html(function (index, html) { 
       return html.replace(re, list_to_replace[item]); 
      }); 
     }); 
     postRows.push($(domClone).html()); 
    }); 
    return postRows; 
} 

编辑:很抱歉的混乱。这应该可行,但我会指出它会返回克隆的文本,但它不会执行替换,因为它正在处理克隆。

+0

谢谢,@JonathanCard。 Object.Keys()如何工作?我以前从来没有见过。 – Alex

+1

它列出了散列表中的键。该行的目的是迭代您想要替换的项目,以便您查找要替换的项目。从这里得到它:http://stackoverflow.com/questions/18912/how-to-find-keys-of-a-hash –

+0

请参阅上面更新@JonathanCard。答案中的代码不起作用。它会引发错误。 – Alex