2011-01-19 19 views
1

我再次試圖取代在頁面中使用JavaScript和jQuery每個控件的每個文本內容的每個HTML控件的內容。更換JavaScript的jQuery的

我需要在每個文本內容(沒有對矯正標籤,只有文本)任何文字來搜索和與其他任何詞替換它。

一次嘗試是:

jQuery.fn.replaceEachOne = function (objective, rep) { 
    this.each(function(){ 
       //$(this).html($(this).html().replace(new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep)); 
    $(this).html($(this).html().replace(new RegExp('('+objective+'(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep)); 
      } 
     ); 
} 

請幫助!

回答

1

像這樣的東西應該做的伎倆:

$.fn.replaceEachOne = function(search, replace) { 
    this.contents().each(function(){ 
     if (this.nodeType == Node.ELEMENT_NODE) { 
      $(this).replaceEachOne(search, replace); 
     } else if (this.nodeType == Node.TEXT_NODE) { 
      this.nodeValue = this.nodeValue.replace(search, replace); 
     } 
    }); 
}; 

這不會對文本的直接更換節點,而不是修改整個元素的HTML。請注意,它區分大小寫。如果您需要不區分大小寫的搜索,則需要將呼叫更改爲replace以使用正則表達式。

+0

那是工作,但我有一個新的控件添加到瑤池的文字,我的意思是補充:<標籤顏色=「...」>瑤池文本 如果我這樣做,瀏覽器不認爲它是控制,只是作爲文本,我的意思是,它在文本上顯示不是具有不同顏色的酷標籤...... :( help !! – Caipivara 2011-01-19 14:31:18

+0

@Daniel GR聽起來像你需要[高亮插件](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html)。 – lonesomeday 2011-01-19 14:49:44

0

我想通過這樣的開始:

jQuery.fn.replaceEachOne = function(objective, rep) { 
    var html = jQuery(this).html(); 
    var simpleRegexp = new RegExp(objective, "gi"); 
    var regexp = new RegExp(">[^><]*?"+objective+"[^><]*?<","gi"); 
    html = html.replace(regexp, function(match) { 
     return match.replace(simpleRegexp, rep); 
    }); 
    jQuery(this).html(html); 
} 

該代碼發現身體的html代碼匹配的文本beetween '>''<'字符,然後替換匹配的文本。

當然,這是簡單的解決方案,它也將取代<script><style>塊文本。我認爲這是一個好主意,首先。

0

最後...

jQuery.fn.replaceEachOne = function (objective, reposition) { 
    this.contents().each(function(){ 
     if (this.nodeType == Node.ELEMENT_NODE) { 
      $(this).replaceEachOne(objective, reposition); 
     } else if (this.nodeType == Node.TEXT_NODE) { 
      var label = document.createElement("label"); 
      label.innerHTML = this.nodeValue.replace(objective, reposition); 
      this.parentNode.insertBefore(label, this); 
      this.parentNode.removeChild(this); 
     } 
    }); 
}