如何在 HTML 中插入变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18032852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:50:13  来源:igfitidea点击:

How to insert variable into HTML

javascripthtmldom

提问by Cheese

I'm having a little problem, i have a translations JSON variable. And i want to put it on HTML. Is there a way to make it somehow?

我有一个小问题,我有一个翻译 JSON 变量。我想把它放在 HTML 上。有没有办法让它以某种方式?

My JS file:

我的JS文件:

var Karting = Karting || {};

Karting = {

lang : 'lv',
translationsLV: {
    "Home" : "Zi?as",
},
}

And i want to do this:

我想这样做:

My page is static and i'm not using any templating engines.

我的页面是静态的,我没有使用任何模板引擎。

<li><a class="active" href="#">Karting.translationsLV['Home']</a></li>

EDIT:

编辑:

Added this:

添加了这个:

$(window).load( function() {
        var translations;
        if (Karting.lang=='lv')
        {
            translations = Karting.translationsLV;
        }
        else
        {
            translations = Karting.translationsENG;
        }
            }, false );

This doesn't show my element

这不显示我的元素

document.write(translations['Home'])

UncaughtRefferenceError - translations is not defined

UncaughtRefferenceError - 翻译未定义

回答by Cherniv

One way is to use document.write:

一种方法是使用document.write

<li><a class="active" href="#"><script>document.write(Karting.translationsLV['Home'])</script></a></li>

回答by iConnor

Simply use innerHTML for this case.

在这种情况下只需使用innerHTML。

var Karting = {
   lang : 'lv',
   translationsLV: {
      Home: "Zi?as"
   }
},
homeInfo = document.getElementById('homeInfo');
homeInfo.innerHTML = Karting.translationsLV.Home;

HTML:

HTML:

<li><a id="homeInfo" class="active" href="#"></a></li>

回答by Deepak Gangore

First of all your JSON is not correct. There is an extra comma there. It should be

首先,您的 JSON 不正确。那里有一个额外的逗号。它应该是

{
lang : 'lv',
translationsLV: {
   "Home" : "Zi?as",
}
}