JS 實現中英文翻譯


     缺點就是還是會閃出中文,但是效果還行。

    

    var langPackage = {
"主題":"Title",
    "下一頁":"NextPage",
    "末頁":"LastPage",
    "首頁":" FirstPage ",
    "上一頁":" PreviousPage ",
    "待辦工作":"MyTasks",
    "中":"Middle",
    "每頁":" EachPage ",
    "條":" Record ",
    "共":" Total ",
    "頁":" Page ",
    "第":" Current ",
    "工作主題":" ProcTitle"
    };

 

執行遍歷 DOM 的邏輯

    /* 
        主調函數
        在 Jquery的 .read方法里調用 ReplaceChildChs($(document));
        或者頁面的最后調用
        ReplaceChildChs($(document));
    */
    function ReplaceChildChs(nodeObj){
        // if($("#hdfUseLang").val()=="CN")return;
        if (nodeObj.children().length > 0){
            nodeObj.children().each(function(){
               ReplaceChildChs($(this));
    //            if ($(this)[0].nodeName.toUpperCase() == "TD"){
                FindChsAndReplaceIt($(this));
    //            }
            });
        } else {
            FindChsAndReplaceIt(nodeObj);
        }
    }

    // 直接替換html 的一種設想,但總是報錯
    function JustReplaceChsDom(nodeObj){
        var pat = new RegExp("[\u4e00-\u9fa5]+","g"); // 匹配中文的正則表達式
        var str = $(nodeObj).html();
        while((arr = pat.exec(str)) != null){
            if (langPackage[arr[0]]){
                str = str.replace(arr[0], langPackage[arr[0]]);
            }
        }
        $(nodeObj).html(str);
    }

    function FindChsAndReplaceIt(nodeObj){
        var pat = new RegExp("[\u4e00-\u9fa5]+","g");
        if ((nodeObj.text() || nodeObj.val() || nodeObj.attr("title")) 
            && (pat.exec(nodeObj.text()) || pat.exec(nodeObj.val()) || pat.exec(nodeObj.attr("title")) )){
            var str = ""
            if (nodeObj.text()){
                str = nodeObj.text();
                ReplaceValue(str, nodeObj, "text");
            }
            if (nodeObj.val()){
                str = nodeObj.val();
                ReplaceValue(str, nodeObj, "val");
            }
            if (nodeObj.attr("title")){
                str = nodeObj.attr("title");
                ReplaceValue(str, nodeObj, "title");
            }
        }
    } 

    function ReplaceValue(str, nodeObj, attrType){
      var arr;
      var pat = new RegExp("[\u4e00-\u9fa5]+","g");
      while((arr = pat.exec(str)) != null){
        if (langPackage[arr[0]]){
            str = str.replace(arr[0], langPackage[arr[0]]);
            
            if (attrType == "text"){
                nodeObj.text(str);
            }
            else if (attrType == "val"){
                nodeObj.val(str);
            }
            else if (attrType == "title"){
                nodeObj.attr("title", str);
            }
        }
      }
    }

ReplaceChildChs($(document));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM