html js中如何取实际写入的值

如何解决html js中如何取实际写入的值

我正在使用 following 库在我的测试网站中实现多语言。不过也有一些不足之处,以我的经验不足,难以解决。

脚本的工作方式是,我们有一个默认语言,它直接写入 html,并为其他语言制作字典(它们位于 js 代码的最后)。除了标题,一切正常。当我们想切换到默认语言时,标题不会改变,只有重新加载页面后才会改变。

最有可能的,问题在于以下代码段(184-186行):

if (langDict["Title"] != null) {
  document.title = langDict["Title"];
}

我想我们需要添加 else 并以某种方式为其设置一个写入 html 本身的值,而不是在翻译中更改了哪个 js。

var languative;
(function (languative) {
    var phraseIdAttr = "data-phrase-id";

    languative.ignoreTags = {
        img: "<img />",br: "<br />",hr: "<hr />"
    };

    languative.dictonaries = {
        html: {
            _id: "html",_name: "HTML"
        },en: {
            _id: "en",_name: "English"
        },ru: {
            _id: "ru",_name: "Русский - Russian"
        },de: {
            _id: "de",_name: "Deutsche - German"
        }
    };

    languative.selectedDictionary = null;

    function getDictionary(langKey) {
        langKey = langKey.toLowerCase();
        if (langKey in languative.dictonaries)
            return languative.dictonaries[langKey];

        var sep = langKey.indexOf("-");
        if (sep > 0)
            langKey = langKey.substring(0,sep);
        return languative.dictonaries[langKey];
    }
    languative.getDictionary = getDictionary;

    function getPhrase(phraseId) {
        var res = findPhrase(phraseId);
        if (res)
            return res; else
            return phraseId;
    }
    languative.getPhrase = getPhrase;

    function findPhrase(phraseId) {
        if ((phraseId == null) || (phraseId == ""))
            return null;

        if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
            return languative.selectedDictionary[phraseId];
        if (phraseId in languative.dictonaries.html)
            return languative.dictonaries.html[phraseId];

        return null;
    }
    languative.findPhrase = findPhrase;

    function getYesNo(value) {
        if (value === undefined)
            return getPhrase("undefined"); else if (value)
            return getPhrase("yes"); else
            return getPhrase("no");
    }
    languative.getYesNo = getYesNo;

    function getAttr(node,attr) {
        var result = (node.getAttribute && node.getAttribute(attr)) || null;
        if (!result && node.attributes) {
            for (var i = 0; i < node.attributes.length; i++) {
                var attrNode = node.attributes[i];
                if (attrNode.nodeName === attr)
                    return attrNode.nodeValue;
            }
        }
        return result;
    }

    function getDictionaryFromHtml() {
        function getNodeValue(node) {
            var res = null;
            if ("innerHTML" in node) {
                res = node["innerHTML"];
            } else {
                res = node.nodeValue;
            }
            if (res != null) {
                res = res.replace(/\s{2,}/g,' ');
                res = res.replace(/^\s+|\s+$/g,'');
            }
            return res;
        }

        function getTagPhrase(tag) {
            if (tag.childNodes.length > 1) {
                var resPhrase = new Array();
                for (var ci = 0; ci < tag.childNodes.length; ci++) {
                    var chNode = tag.childNodes[ci];
                    var chName = chNode.nodeName.toLowerCase();
                    var chValue = null;

                    if (chName in languative.ignoreTags)
                        chValue = languative.ignoreTags[chName]; else
                        chValue = getNodeValue(chNode);

                    resPhrase.push(chValue);
                }
                return resPhrase;
            } else {
                return getNodeValue(tag);
            }
        }

        var tags = getHtmlTags();

        var resDict = new Object();
        for (var ti = 0; ti < tags.length; ti++) {
            var tag = tags[ti];
            var phraseId = getAttr(tag,phraseIdAttr);
            if ((phraseId != null)) {
                var phraseValue = getTagPhrase(tag);
                if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
                    console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId],null,"  ") + "\n 2: " + JSON.stringify(phraseValue,"  "));
                } else {
                    resDict[phraseId] = phraseValue;
                }
            }
        }
        return resDict;
    }
    languative.getDictionaryFromHtml = getDictionaryFromHtml;

    function changeLanguage(langKey) {
        function setTagPhrase(tag,phrase) {
            if (tag.childNodes.length > 1) {
                for (var ci = 0; ci < tag.childNodes.length; ci++) {
                    var chNode = tag.childNodes[ci];
                    var nName = chNode.nodeName.toLowerCase();
                    if (!(nName in languative.ignoreTags)) {
                        if ("innerHTML" in chNode) {
                            chNode["innerHTML"] = " " + phrase[ci] + " ";
                        } else {
                            chNode.nodeValue = " " + phrase[ci] + " ";
                        }
                    }
                }
            } else {
                tag.innerHTML = " " + phrase + " ";
            }
        }


        var langDict = languative.getDictionary(langKey);
        if (langDict == null) {
            console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
            langDict = languative.dictonaries.html;
        }
        languative.selectedDictionary = langDict;

        var tags = getHtmlTags();
        for (var ti = 0; ti < tags.length; ti++) {
            var tag = tags[ti];
            var phraseId = getAttr(tag,phraseIdAttr);
            if ((phraseId != null)) {
                var phraseValue = languative.getPhrase(phraseId);
                if (phraseValue) {
                    setTagPhrase(tag,phraseValue);
                } else {
                    console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
                }
            }
        }

        if (langDict["Title"] != null) {
            document.title = langDict["Title"];
        }
    }
    languative.changeLanguage = changeLanguage;

    function getHtmlTags() {
        var res = new Array();
        var docTags = document.body.getElementsByTagName("*");

        for (var i = 0; i < docTags.length; i++) {
            var docTag = docTags[i];
            var phraseId = getAttr(docTag,phraseIdAttr);
            if (phraseId)
                res.push(docTag);
        }
        return res;
    }

    var initialized = false;

    function init() {
        if (!initialized) {
            initialized = true;
            var htmlDict = languative.getDictionaryFromHtml();

            for (var dictKey in htmlDict) {
                if (!(dictKey in languative.dictonaries.html)) {
                    languative.dictonaries.html[dictKey] = htmlDict[dictKey];
                }
            }
            var nav = window.navigator;
            languative.changeLanguage(nav.userLanguage || nav.language);
        }
    }
    languative.init = init;

    function modifyDictionary(langKey,dictModifications) {
        var langDict = languative.getDictionary(langKey);
        if (langDict == null) {
            languative.dictonaries[langKey.toLowerCase()] = dictModifications;
        } else {
            for (var dictKey in dictModifications) {
                langDict[dictKey] = dictModifications[dictKey];
            }
        }
    }
    languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));

if (document.addEventListener)
    document.addEventListener('DOMContentLoaded',languative.init);

if (window.addEventListener) {
    window.addEventListener('load',languative.init,false);
} else {
    window.attachEvent('onload',languative.init);
}

languative.modifyDictionary("ru",{
            Title: "Заголовок",firstmessage: "ЭТО ЯЗЫК ПО УМОЛЧАНИЮ",secondmessage: "КАКОЙ ТО ДРУГОЙ ТЕКСТ",thirdmessage: "ЧТО ТО ЕЩЕ"
        });
        languative.modifyDictionary("de",{
            Title: "Überschrift",firstmessage: "Dies ist die Standardsprache",secondmessage: "JEDER ANDERE TEXT",thirdmessage: "ETWAS ANDERES"
        });
<ul>
        <li><a href="#" onclick="languative.changeLanguage('en');" data-phrase-id="english">English</a></li>
        <li><a href="#" onclick="languative.changeLanguage('ru')" data-phrase-id="russian">Russian</a></li>
        <li><a href="#" onclick="languative.changeLanguage('de')" data-phrase-id="german">German</a></li>
    </ul>
<h1 data-phrase-id="firstmessage">THIS IS THE DEFAULT LANGUAGE</h1>
<span data-phrase-id="secondmessage">ANY OTHER TEXT</span>
<p data-phrase-id="thirdmessage">SOMETHING ELSE</p>

也在我的网站上有一个反馈表。我希望可以翻译 placeholder 值。怎么做?

我是这样理解的,但这是一个好方法吗?

if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
    document.querySelector("input[name=name]").placeholder = "Name";
    document.querySelector("input[name=subject]").placeholder = "Thema";
    document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
    document.querySelector("input[name=name]").placeholder = "Имя";
    document.querySelector("input[name=subject]").placeholder = "Тема";
    document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
    document.querySelector("input[name=name]").placeholder = "Name";
    document.querySelector("input[name=subject]").placeholder = "Subject";
    document.querySelector("input[name=message]").placeholder = "Message";
};
document.querySelector('.lang').onclick = function() {
    if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
        document.querySelector("input[name=name]").placeholder = "Name";
        document.querySelector("input[name=subject]").placeholder = "Thema";
        document.querySelector("input[name=message]").placeholder = "Brief";
    } else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
        document.querySelector("input[name=name]").placeholder = "Имя";
        document.querySelector("input[name=subject]").placeholder = "Тема";
        document.querySelector("input[name=message]").placeholder = "Сообщение";
    } else {
        document.querySelector("input[name=name]").placeholder = "Name";
        document.querySelector("input[name=subject]").placeholder = "Subject";
        document.querySelector("input[name=message]").placeholder = "Message";
    };
};

var languative;
(function (languative) {
    var phraseIdAttr = "data-phrase-id";

    languative.ignoreTags = {
        img: "<img />",{
            name: "Ваше имя",email: "Ваш email",send: "Отправить сообщение"
        });
        languative.modifyDictionary("de",{
            name: "Ihr Name",email: "Deine E-Mail",send: "Nachricht senden"
        });
ul li{
 list-style: none;
}
    <ul>
            <li><a href="#" onclick="languative.changeLanguage('en');" data-phrase-id="english">English</a></li>
            <li><a href="#" onclick="languative.changeLanguage('ru')" data-phrase-id="russian">Russian</a></li>
            <li><a href="#" onclick="languative.changeLanguage('de')" data-phrase-id="german">German</a></li>
        </ul>
        
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>

解决方法

对于第一个片段,您应该只为包含 enTitle 添加一个字典,它会起作用,如下所示:

languative.modifyDictionary("en",{
    Title: "Caption",});

对于第二个,有更多的工作,因为您的脚本更改了 innerHTML,这不适合您的反馈表单,因为它只包含没有 innerHTML 的输入元素,因此脚本应该相应地修改,如下所示:

var languative;
(function (languative) {
    var phraseIdAttr = "data-phrase-id";

    languative.ignoreTags = {
        img: "<img />",br: "<br />",hr: "<hr />"
    };

    languative.dictonaries = {
        html: {
            _id: "html",_name: "HTML"
        },en: {
            _id: "en",_name: "English"
        },ru: {
            _id: "ru",_name: "Русский - Russian"
        },de: {
            _id: "de",_name: "Deutsche - German"
        }
    };

    languative.selectedDictionary = null;

    function getDictionary(langKey) {
        langKey = langKey.toLowerCase();
        if (langKey in languative.dictonaries)
            return languative.dictonaries[langKey];

        var sep = langKey.indexOf("-");
        if (sep > 0)
            langKey = langKey.substring(0,sep);
        return languative.dictonaries[langKey];
    }
    languative.getDictionary = getDictionary;

    function getPhrase(phraseId) {
        var res = findPhrase(phraseId);
        if (res)
            return res; else
            return phraseId;
    }
    languative.getPhrase = getPhrase;

    function findPhrase(phraseId) {
        if ((phraseId == null) || (phraseId == ""))
            return null;

        if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
            return languative.selectedDictionary[phraseId];
        if (phraseId in languative.dictonaries.html)
            return languative.dictonaries.html[phraseId];

        return null;
    }
    languative.findPhrase = findPhrase;

    function getYesNo(value) {
        if (value === undefined)
            return getPhrase("undefined"); else if (value)
            return getPhrase("yes"); else
            return getPhrase("no");
    }
    languative.getYesNo = getYesNo;

    function getAttr(node,attr) {
        var result = (node.getAttribute && node.getAttribute(attr)) || null;
        if (!result && node.attributes) {
            for (var i = 0; i < node.attributes.length; i++) {
                var attrNode = node.attributes[i];
                if (attrNode.nodeName === attr)
                    return attrNode.nodeValue;
            }
        }
        return result;
    }

    function getDictionaryFromHtml() {
        function getNodeValue(node) {
            var res = null;
            if (node.tagName !== 'INPUT') {
              if ("innerHTML" in node) {
                  res = node["innerHTML"];
              } else {
                  res = node.nodeValue;
              }
            } else {
              res = node.getAttribute("placeholder") || node.value;
            }
            if (res != null) {
                res = res.replace(/\s{2,}/g,' ');
                res = res.replace(/^\s+|\s+$/g,'');
            }
            return res;
        }

        function getTagPhrase(tag) {
            if (tag.childNodes.length > 1) {
                var resPhrase = new Array();
                for (var ci = 0; ci < tag.childNodes.length; ci++) {
                    var chNode = tag.childNodes[ci];
                    var chName = chNode.nodeName.toLowerCase();
                    var chValue = null;

                    if (chName in languative.ignoreTags)
                        chValue = languative.ignoreTags[chName]; else
                        chValue = getNodeValue(chNode);

                    resPhrase.push(chValue);
                }
                return resPhrase;
            } else {
                return getNodeValue(tag);
            }
        }

        var tags = getHtmlTags();

        var resDict = new Object();
        for (var ti = 0; ti < tags.length; ti++) {
            var tag = tags[ti];
            var phraseId = getAttr(tag,phraseIdAttr);
            if ((phraseId != null)) {
                var phraseValue = getTagPhrase(tag);
                if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
                    console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId],null,"  ") + "\n 2: " + JSON.stringify(phraseValue,"  "));
                } else {
                    resDict[phraseId] = phraseValue;
                }
            }
        }
        return resDict;
    }
    languative.getDictionaryFromHtml = getDictionaryFromHtml;

    function changeLanguage(langKey) {
        function setTagPhrase(tag,phrase) {
            if (tag.childNodes.length > 1) {
                for (var ci = 0; ci < tag.childNodes.length; ci++) {
                    var chNode = tag.childNodes[ci];
                    var nName = chNode.nodeName.toLowerCase();
                    if (!(nName in languative.ignoreTags)) {
                    console.log(chNode.tagName)
                        if (chNode.tagType !== 'INPUT') {
                          if ("innerHTML" in chNode) {
                              chNode["innerHTML"] = " " + phrase[ci] + " ";
                          } else {
                              chNode.nodeValue = " " + phrase[ci] + " ";
                          }
                        } else {
                          chNode.hasAttribute("placeholder")
                            ? chNode.setAttribute("placeholder",phrase[ci])
                            : chNode.value = phrase[ci];
                        }
                    }
                }
            } else {
                if (tag.tagName !== 'INPUT') {
                  tag.innerHTML = " " + phrase + " ";
                } else {
                tag.hasAttribute("placeholder")
                  ? tag.setAttribute("placeholder",phrase)
                  : tag.value = phrase;
                }
            }
        }


        var langDict = languative.getDictionary(langKey);
        if (langDict == null) {
            console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
            langDict = languative.dictonaries.html;
        }
        languative.selectedDictionary = langDict;

        var tags = getHtmlTags();
        for (var ti = 0; ti < tags.length; ti++) {
            var tag = tags[ti];
            var phraseId = getAttr(tag,phraseIdAttr);
            if ((phraseId != null)) {
                var phraseValue = languative.getPhrase(phraseId);
                if (phraseValue) {
                    setTagPhrase(tag,phraseValue);
                } else {
                    console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
                }
            }
        }

        if (langDict["Title"] != null) {
            document.title = langDict["Title"];
        }
    }
    languative.changeLanguage = changeLanguage;

    function getHtmlTags() {
        var res = new Array();
        var docTags = document.body.getElementsByTagName("*");

        for (var i = 0; i < docTags.length; i++) {
            var docTag = docTags[i];
            var phraseId = getAttr(docTag,phraseIdAttr);
            if (phraseId)
                res.push(docTag);
        }
        return res;
    }

    var initialized = false;

    function init() {
        if (!initialized) {
            initialized = true;
            var htmlDict = languative.getDictionaryFromHtml();

            for (var dictKey in htmlDict) {
                if (!(dictKey in languative.dictonaries.html)) {
                    languative.dictonaries.html[dictKey] = htmlDict[dictKey];
                }
            }
            var nav = window.navigator;
            languative.changeLanguage(nav.userLanguage || nav.language);
        }
    }
    languative.init = init;

    function modifyDictionary(langKey,dictModifications) {
        var langDict = languative.getDictionary(langKey);
        if (langDict == null) {
            languative.dictonaries[langKey.toLowerCase()] = dictModifications;
        } else {
            for (var dictKey in dictModifications) {
                langDict[dictKey] = dictModifications[dictKey];
            }
        }
    }
    languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));

if (document.addEventListener)
    document.addEventListener('DOMContentLoaded',languative.init);

if (window.addEventListener) {
    window.addEventListener('load',languative.init,false);
} else {
    window.attachEvent('onload',languative.init);
}

languative.modifyDictionary("ru",{
            name: "Ваше имя",email: "Ваш email",send: "Отправить сообщение"
        });
        languative.modifyDictionary("de",{
            name: "Ihr Name",email: "Deine E-Mail",send: "Nachricht senden"
        });
ul li{
 list-style: none;
}
<ul>
            <li><a href="#" onclick="languative.changeLanguage('en');" data-phrase-id="english">English</a></li>
            <li><a href="#" onclick="languative.changeLanguage('ru')" data-phrase-id="russian">Russian</a></li>
            <li><a href="#" onclick="languative.changeLanguage('de')" data-phrase-id="german">German</a></li>
        </ul>
        
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-