3

In HTML, I have some images and a javascript function.

<img onmouseover="repl()" class="EN" ... />
<img onmouseover="repl()" class="FR" ... />
...

When user is on an image. I want to change my header text according to the language selected.

I need a way to have a "reference" to the sender of my function in javascript. But I have no idea because I have not used javascript for years. Please Help me !

function repl() {

    // Missing Solution 
    // var lang = sender.attr("class"); <= Please correct me

    var headerText = "";
    if (lang == 'FR') {
        headerText = "Cliquez sur le drapeau"
    } else {
        headerText = "Click on flag"
    }
4

4 回答 4

6

最好的解决方案是使用addEventListener. 将所有图像归为同一类,选择它们,然后添加事件。我还建议使用data-*属性来存储语言。

<img class="repl" data-lang="EN" ... />
<img class="repl" data-lang="FR" ... />

然后在你的 JavaScript 中:

window.onload = function(){// Make sure DOM is ready
    // Get the images
    var imgs = document.getElementsByClassName('repl');

    // Loop over them
    for(var i = 0, len = imgs.length; i < len; i++){
        // Add the event
        imgs[i].addEventListener('mouseover', function(){
            // Get the language. "this" is the element we hovered over
            var lang = this.getAttribute('data-lang');

            var headerText = "";
            if (lang == 'FR') {
                headerText = "Cliquez sur le drapeau"
            } else {
                headerText = "Click on flag"
            }
        });
    }
};

演示:http: //jsfiddle.net/cT7Tj/1/

于 2013-09-04T15:21:58.653 回答
2

首先,您需要将发件人发送到您的函数:

<img onmouseover="repl(this)" class="EN" ...

然后:

function repl(sender) {
//you have the element that sent the event
    var lang = sender.getAttribute('data-lang');
    var headerText = "";
    if (lang == 'FR') {
        headerText = "Cliquez sur le drapeau"
    } else {
        headerText = "Click on flag"
    }
}
于 2013-09-04T15:21:54.307 回答
0

var lang = this.getAttribute('class');

您应该使用“data-lang”属性。

于 2013-09-04T15:20:04.080 回答
-1
    function repl() {

   var lang = navigator.language || navigator.userLanguage; //this will fetch the current browser language   
   var headerText = "";

   switch (lang) {
       case 'fr':
           document.getElementById('your_id').innerHTML = "Cliquez sur le drapeau";
           break;
       default:
           document.getElementById('your_id').innerHTML = "Click on flag"
   }
于 2013-09-04T15:18:54.003 回答