简体   繁体   English

如何基于匹配数组中的值来显示特定图像?

[英]How do I display a certain image based on matching a value in an array?

I'm trying to develop a bit of JavaScript that will detect the language of a browser (trivial as it uses navigator.Browserlanguage and window.navigator.language ) and based upon this will display a certain image to the user. 我正在尝试开发一些JavaScript,以检测浏览器的语言(使用navigator.Browserlanguagewindow.navigator.language ),并以此为基础向用户显示特定图像。 For example, if the browser language is "en-GB" it will display a certain image and if it's "fr" then it will display a different image and so on. 例如,如果浏览器语言是“ en-GB”,它将显示特定图像,如果是“ fr”,则将显示其他图像,依此类推。

Currently the code I've got loops through the array to detect browser language and displays "language supported". 目前,我所拥有的代码遍历整个数组以检测浏览器语言并显示“支持的语言”。 It works fine as I've tested it in FF, IE, Chrome, Safari and Opera but now I need to know if there is a way for me to display an image based on what the browser language is. 当我在FF,IE,Chrome,Safari和Opera中对其进行测试时,它可以正常工作,但是现在我需要知道是否有一种方法可以根据浏览器语言显示图像。 Is there a way for me to do this? 我有办法吗? Ie do I link 2 arrays together (is this even possible?) or can I just use an array of images and have the corresponding images the same position in the array as the text? 即我可以将2个数组链接在一起(甚至可以吗?)还是可以只使用图像数组并使对应的图像与文本在数组中的位置相同? How would I go about achieving this? 我将如何实现这一目标?

Here's the code I've got so far: 这是到目前为止我得到的代码:

var IAB_Array = new Array("en","en-GB","en-US","fr","de","en-gb","en-us"); 
var lang = IAB_lang_detect(); 
if(lang) document.write('Language supported');

function IAB_lang_detect() {
    if ((navigator.browserLanguage) || (window.navigator.language)) {
    for (var i=0;i<IAB_Array.length;i++) {
        if((IAB_Array[i]==navigator.browserLanguage) || (IAB_Array[i]==window.navigator.language)) {
            return true;
        }
    }
}
return false;
}

Any help would be much appreciated! 任何帮助将非常感激!

Thanks 谢谢

Instead of using strings inside of the array, insert an object: 插入一个对象,而不是在数组内部使用字符串:

IAB_Array = [
  {lang: "en", image: "english.png"},
  {lang: "en-GB", image: "en_gb.png"},
  ...
];

You can then find the properties of that object using IAB_Array.lang or IAB_Array["lang"] . 然后,您可以使用IAB_Array.langIAB_Array["lang"]查找该对象的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM