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

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

问题描述:

我正在尝试开发一些JavaScript,以检测浏览器的语言(这很简单,因为它使用 navigator.Browserlanguage window.navigator.language )并以此为基础向用户显示特定图像.例如,如果浏览器语言是"en-GB",它将显示一个特定的图像,如果它是"fr",则将显示一个不同的图像,依此类推.

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. 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.

目前,我所拥有的代码遍历数组以检测浏览器语言并显示支持的语言".当我在FF,IE,Chrome,Safari和Opera中对其进行测试时,它工作正常,但是现在我需要知道是否有一种方法可以根据浏览器语言显示图像.我有办法吗?IE.我可以将2个数组链接在一起(甚至可以吗?)还是可以只使用一个图像数组并使对应的图像在数组中与文本的位置相同?我将如何实现这一目标?

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. Is there a way for me to do this? I.e. 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? 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;
}

任何帮助将不胜感激!

谢谢

而不是在数组内部使用字符串,而是插入一个对象:

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"},
  ...
];

然后您可以使用 IAB_Array.lang IAB_Array ["lang"] 查找该对象的属性.

You can then find the properties of that object using IAB_Array.lang or IAB_Array["lang"].