English 中文(简体)
无法从外部 JS 文件装入 HTML 文件的密钥/ 价对价
原标题:Unable to load Key/Value Pair in HTML file from external JS file

以下是 index.html 文件:

<html>

<head>

<script>

function ChangePageLanguage()
{
var e = document.getElementById("langDD");
var lang = e.options[e.selectedIndex].value;

if (lang == "it")
{
    var scrptE = document.createElement("script");
    scrptE.setAttribute("type", "text/javascript");
    scrptE.setAttribute("language", "JavaScript");
    scrptE.setAttribute("src", "language_it.js?" + (Date.now() % 10000));
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(scrptE);

    document.getElementById( p1 ).innerHTML = obj[key1];
    //document.getElementById( p2 ).innerHTML = obj[key2];
}
}
</script>
</head>

<body>
<select onchange="ChangePageLanguage()" id="langDD">
    <option value="en">English</option>
    <option value="it">Italian</option>
</select>
<br/>
<span id="p1">
</span>
<br/>
<span id="p2">
</span>

</body>

</html>

我有以下的 language_it.js :

var obj = {
key1: Il mio nome è Azeem,
key2: Sono uno sviluppatore di Software
};

When I select Italian Language from Dropdown, it should print key1 value in span object with id="p1", but its not... Is there anything wrong with key/value pairs in language_it.js? Please help me out.

问题回答

脚本将装入 Aync, 所以当您尝试访问 < code> obj 时, 它尚未可用 。 尝试使用诸如 < code> require. js 或一个负载处理器 :

scrptE.onload = scrptE.onreadystatechange = function() {
    console.log(obj);
};

您想要在事件处理器中装入脚本文件自动同步有什么具体原因吗? 将它载入到加载中并在需要时立即访问似乎更有效率 。

您张贴的 Javascript 文件是非法的, 因为您没有引用字符串字典 。 应该是这样 :

var obj = {
  key1:  Il mio nome è Azeem ,
  key2:  Sono uno sviluppatore di Software 
};

<强 > 更新

还有,线线线

document.getElementById( p1 ).innerHTML = obj[key1];

错误, 因为 key1 不是一个变量( 正如错误消息所言 ) 。

应将以下任何一种变式改写为:

document.getElementById( p1 ).innerHTML = obj.key1;
document.getElementById( p1 ).innerHTML = obj[ key1 ];

这两行是等效的。 如果这是您的新消息, 那么我建议您开始阅读一个恰当的 Javascript 教程 。 < a href=" https:// stackoverflow. com/tags/javascript/ info>> javascript 标签, sinfo page 是一个很好的起点 。





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签