我已经编写了一个基于浏览器语言填充URL(包含图像)的函数。然后将此后续URL写入变量。所有的图像都是基于语言的,所以对于德国来说,它将是“de.gif”,法国将是“fr.gif”等等。
我的问题是如何在HTML页面中调用此变量?
为了帮助我在这里更好地说明这个问题,请注意这是一个在此HTML页面中调用的EXTERNAL .js文件:
function IABEU_moused_detect() {
(function IAB_lang_detect() {"use strict";
var IAB_lang_map = {"de-at": "at","nl-be": "be-nl","fr-be": "be-fr","da": "den","de": "de","hu": "hu","en-ie": "ie","ga": "ie","es": "es","fr": "fr","it": "it","nl": "nl","no": "nor","pl": "pl","en": "uk","en-GB": "uk","en-US": "uk","en-gb": "uk","en-us": "uk"},
IAB_lang = (navigator && navigator.browserLanguage) || (window.navigator && window.navigator.language) || "en-GB";
IAB_url = ("http://www.someurl.com/" + IAB_lang_map[IAB_lang]);
IAB_img = ("http://www.myimagesarehere.com/" + IAB_lang_map[IAB_lang]+".gif");
}());}
所以我想在我的HTML页面中调用IAB_img变量(它是.js文件中的全局变量)
HTML在这里:
<div>
<img src="HERE IS WHERE I WANT TO call the variable 'IAB_img'">
</div>
由于
编辑:所以我仍然无法解决这个问题,有没有办法让我在“IAB_img”中将值用作我的HTML文件中的图像src?
答案 0 :(得分:2)
我首先给图片一个id。
<div>
<img id="TheImage" src="HERE IS WHERE I WANT TO call the variable 'IAB_img'">
</div>
然后在你的JavaScript函数中,只需分配图像的src:
function IABEU_moused_detect() {
(function IAB_lang_detect() {"use strict";
var IAB_lang_map = {"de-at": "at","nl-be": "be-nl","fr-be": "be-fr","da": "den","de": "de","hu": "hu","en-ie": "ie","ga": "ie","es": "es","fr": "fr","it": "it","nl": "nl","no": "nor","pl": "pl","en": "uk","en-GB": "uk","en-US": "uk","en-gb": "uk","en-us": "uk"},
IAB_lang = (navigator && navigator.browserLanguage) || (window.navigator && window.navigator.language) || "en-GB";
IAB_url = ("http://www.someurl.com/" + IAB_lang_map[IAB_lang]);
IAB_img = ("http://www.myimagesarehere.com/" + IAB_lang_map[IAB_lang]+".gif");
var image = document.getElementById('TheImage');
image.src = IAB_img;
}());}
答案 1 :(得分:0)
您是否通过模板呈现html页面?如果是这样,您可以包含一个带有变量设置的javascript片段,以便进一步阅读:
<script type="text/javascript">
var IAB_img = {{value}};
</script>
只需在加载其他脚本之前加上它,然后就会为您定义IAB_img。
答案 2 :(得分:-1)
这样的事情:
<div>
<img src="javascript:document.write(IAB_img);" />
</div>