簡體   English   中英

替換每個HTML控件的內容javascript jquery

[英]Replace content of each HTML controls javascript jquery

我再次嘗試使用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) );
            }
        );
}

請幫忙!!

這樣的事情應該可以解決問題:

$.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為使用正則表達式。

我將從這樣的事情開始:

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代碼中找到匹配的文本,然后替換匹配的文本。

當然,這是簡單的解決方案,它還將替換<script><style>塊中的文本。 我認為這是一個好主意。

最后...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM