最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to insert variable into HTML - Stack Overflow

programmeradmin1浏览0评论

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?

My JS file:

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

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?

My JS file:

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

Share Improve this question edited Aug 3, 2013 at 13:44 putvande 15.2k3 gold badges36 silver badges51 bronze badges asked Aug 3, 2013 at 12:26 DeveloperDeveloper 4,3215 gold badges36 silver badges69 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

One way is to use document.write:

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

Simply use innerHTML for this case.

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

HTML:

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

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

{
lang : 'lv',
translationsLV: {
   "Home" : "Ziņas",
}
}
发布评论

评论列表(0)

  1. 暂无评论