2015-06-03 129 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