首页 > 解决方案 > 用 JavaScript/jQuery 替换 dom 对象中出现的各种字符串的最快、最可靠的方法

问题描述

我编写了一个函数,用 json 数组中的替换替换所有出现的“@TransResource.....”,例如“@TransResource.Contact.Send”。

发生的例子可能是:

<button class="btn btn-primary btn-block js-send">@TransResource.Contact.Send</button>

<input type="text" class="form-control" id="LastName" name="LastName" placeholder="@TransResource.Contact.LastName">

<a href="#">@TransResource.Contact.LastName"</a>

一切都很好,除了 IE/edge 丢失了一些翻译,我不知道为什么。有人可以解决这个问题和/或有更好或更强大的方法吗?

您可以看到,小提琴在 Chrome 中完美运行,但边缘缺少按钮文本翻译。

这是一个小提琴

我的 JavaScript 代码。

var
getLocalResource = function (key) {
    try {
        var retVal = key;
        retVal = StringResource[retVal] === null || StringResource[retVal] === undefined ? retVal : StringResource[retVal];
        return retVal;
    }
    catch (err) {
        console.log(arguments.callee.name + ": " + err);
    }
},
translate = function (node) {
    try {
        var pattern = /@TransResource.[a-zA-Z0-9.]+/g;
        if (!node) node = $("body *");

        node.contents().each(function () {
            if (this.nodeType === 3) {
                this.nodeValue = this.nodeValue.replace(pattern, function (match, entity) {
                    return getLocalResource(match.slice(15));
                });
            }

            if (this.attributes) {
                for (var i = 0, atts = this.attributes, n = atts.length, arr = []; i < n; i++) {
                    if (atts[i].nodeValue !== "") { // Ignore this node it is an empty text node
                        atts[i].nodeValue = atts[i].nodeValue.trim().replace(pattern, function (match, entity) {
                            return getLocalResource(match.slice(15));
                        });
                    }
                }
            }
        });
    }

    catch (err) {
        console.log(arguments.callee.name + ": " + err);
    }
};

和json:

var StringResource = {
    "Contact.EmailAddress": "Email address",
    "Contact.Headline": "Contact",
    "Contact.Description": "please leaf us a message...?",
    "Contact.Teasertext": "Please leaf us a message <b>bold text</b>",
    "Contact.Telephone": "Telephone",
    "Contact.Send": "Send",
    "Page.Contact": "Contact"
};

编辑(现在这是我的解决方案): 感谢@Chris-G,他的评论消除了 IE 问题,也感谢@trincot 的性能更新。现在是这个脚本:

var
getLocalResource = function (key) {
    try {
        var retVal = key;
        retVal = StringResource[retVal] === null || StringResource[retVal] === undefined ? retVal : StringResource[retVal];
        return retVal;
    }
    catch (err) {
        console.log(arguments.callee.name + ": " + err);
    }
},
translate = function (node) {
    try {
        var pattern = /@TransResource.[a-zA-Z0-9.]+/g;
        if (!node) node = $("body *");

        node.contents().each(function () {
            if (this.nodeType === 3 && this.nodeValue.trim().length) {
                var s = this.nodeValue.replace(pattern, function (match, entity) {
                    return getLocalResource(match.slice(15));
                });
                if (this.nodeValue !== s) this.nodeValue = s;
            }

            if (this.attributes) {
                for (var i = 0, atts = this.attributes, n = atts.length, arr = []; i < n; i++) {
                    if (atts[i].nodeValue !== "") { // Ignore this node it is an empty text node
                        atts[i].nodeValue = atts[i].nodeValue.trim().replace(pattern, function (match, entity) {
                            return getLocalResource(match.slice(15));
                        });
                    }
                }
            }
        });
    }

    catch (err) {
        console.log(arguments.callee.name + ": " + err);
    }
};

标签: javascriptjqueryregexreplace

解决方案


IE中的问题是对于textarea节点,当它没有内容时,赋值node.nodeValue会触发异常“无效参数”。不要问我为什么。

如果您甚至在 HTML 中的开始和结束标记之间添加一个空格textarea,错误就会消失,但如果您这样做,占位符属性将变得无用。

但是您也可以通过仅node.nodeValue在分配的值与其当前值不同时分配来解决代码中的问题:

if (this.nodeType === 3) {
    var s = this.nodeValue.replace(pattern, function (match, entity) {
        return getLocalResource(match.slice(15));
    });
    if (this.nodeValue !== s) this.nodeValue = s;
}

推荐阅读