简体   繁体   English

setAttribute、onclick、eventListener 不起作用

[英]setAttribute, onclick, eventListener won't work

So i have this code in javascript that replaces the text from the html, depending on the language you click on ( romanian or english, default is romanian).所以我在 javascript 中有这段代码,它替换了 html 中的文本,具体取决于您单击的语言(罗马尼亚语或英语,默认为罗马尼亚语)。 I tried all of the 3 ways i know for the click action, but none of them work.我尝试了所有我知道的点击操作的 3 种方法,但它们都不起作用。 Can you please help me?你能帮我么?

EDIT:编辑:
The first couple of instructions don't work at all ( nothing happens, not even when clicking on them).前几条指令根本不起作用(没有任何反应,即使点击它们也没有)。 Then, the last bouth couples execute at the onload (but don't work after, when click on them).然后,最后几对夫妇在加载时执行(但在单击它们之后不工作)。 I see that using addEventListener with the listener function doesn't work with other parameters than just the event itself, but I'm still confused about the other ways我看到将 addEventListener 与侦听器函数一起使用不能与其他参数一起使用,而不仅仅是事件本身,但我仍然对其他方式感到困惑

<html lang = "en">
<head>
    <title>
        Website
    </title>
    <meta charset = "UTF-8">
</head>

    <body>

        <a id='english' >English</a>
        <a id='romanian'>Romanian</a>
        <p id="paragraph">
            Bine ai venit pe site-ul meu!
        </p>

        <script>
            localStorage.setItem("languageStored" , "romanian");

            var language = {
                eng: {
                    welcome: "Welcome to my website!"
                },
                ro: {
                    welcome: "Bine ai venit pe site-ul meu!"
                }
            };

            window.onload = function() 
        {
            let optEngl = document.getElementById('english');
            let optRo = document.getElementById('romanian');

         //   optRo.setAttribute('click' ,'languageChange(this , optRo)' );
        //    optEngl.setAttribute('click','languageChange(this , optEngl)');


    //      optEngl.onclick = languageChange(this , optEngl);
    //      optRo.onclick = languageChange(this , optRo);

      //    optEngl.addEventListener("click" , languageChange(this , optEngl));
      //    optRo.addEventListener("click" , languageChange(this , optRo));

        }

        function languageChange(e , obj)
        {
            let languageStored = localStorage.getItem("languageStored");
            if(languageStored != obj.id)
            {
                console.log(obj.id);
                languageStored = obj.id;
                localStorage.setItem("languageStored" , languageStored);

                if(languageStored == "english")
                 document.getElementById('paragraph').textContent = language.eng.welcome;
                else 
                 document.getElementById('paragraph').textContent = language.ro.welcome;
            }
        }    
        </script>
    </body>
</html> ```

.addEventListener takes a callback as the second parameter, so you don't need the () when you're adding your function. .addEventListener将回调作为第二个参数,因此在添加函数时不需要()

Also, you can use this inside the callback function to refer to the Element that the Event triggered from - this just cleans up the function code a little bit - You don't need to includig any parameters to your languageChange function此外,您可以在回调函数中使用this来引用事件触发的元素 - 这只是稍微清理了函数代码 - 您不需要在languageChange函数中包含任何参数

LocalStorage doesn't work with Snippets on this site, so I wrote a quick Codepen to show the changes LocalStorage 不适用于此站点上的 Snippets,因此我编写了一个快速Codepen 来显示更改

localStorage.setItem("languageStored", "romanian");

var language = {
  eng: {welcome: "Welcome to my website!"},
  ro: {welcome: "Bine ai venit pe site-ul meu!"}
};

window.onload = function() {
  let optEngl = document.getElementById('english');
  let optRo = document.getElementById('romanian');

  optEngl.addEventListener('click', languageChange);
  optRo.addEventListener('click', languageChange);
}

function languageChange() {
  // Get the Language stored
  let languageStored = localStorage.getItem("languageStored");

  // You can use `this` rather than `obj` to refer to the Clicked Element
  if (languageStored != this.id) {
    languageStored = this.id;
    localStorage.setItem("languageStored", languageStored);

    if (languageStored == "english")
      document.getElementById('paragraph').textContent = language.eng.welcome;
    else
      document.getElementById('paragraph').textContent = language.ro.welcome;
    }
  }
}

I made couple of changes to your code.First, I think you can directly call functions from a tag and no need of window.onload .我做了一些更改您code.First的,我想你可以直接从调用函数a标签和没有必要的window.onload One issue I found with your code was when you were sending optEngl you were just sending as optEngl without any quotes which made js think it wasn't string.我在您的代码中发现的一个问题是,当您发送optEngl您只是作为optEngl发送而没有任何引号,这使 js 认为它​​不是字符串。 Then, I modified your string comparison within languageChange function using localeCompare rather than == .然后,我使用localeCompare而不是==修改了languageChange函数中的字符串比较。 Then, it worked fine.然后,它工作得很好。 I hope this helps.我希望这有帮助。

<html lang="en">
  <head>
    <title>
      Website
    </title>
    <meta charset="UTF-8">
  </head>

  <body>

    <a id='english' onClick="languageChange(this , 'optEngl');">English</a>
    <a id='romanian' onClick="languageChange(this , 'optRo');">Romanian</a>

    <p id="paragraph">
      Bine ai venit pe site-ul meu!
    </p>

    <script type="text/javascript">
      localStorage.setItem("languageStored", "romanian");

      var language = {
        eng: {
          welcome: "Welcome to my website!"
        },
        ro: {
          welcome: "Bine ai venit pe site-ul meu!"
        }
      };

      function languageChange(e, obj) {
        let languageStored = localStorage.getItem("languageStored");
        if (languageStored != obj) {
          localStorage.setItem("languageStored", obj);
          if (languageStored.localeCompare("optEngl")) {
            document.getElementById('paragraph').textContent = language.eng.welcome;
          } else {
            document.getElementById('paragraph').textContent = language.ro.welcome;
          }
        }
      }

    </script>

  </body>

</html>

If you want to see results, check out jsfiddle snippet如果您想查看结果,请查看jsfiddle片段

By using javascript:通过使用javascript:

<html lang="en">

  <head>
    <title>
      Website
    </title>
    <meta charset="UTF-8">
  </head>

  <body>

    <a id='english'>English</a>
    <a id='romanian'>Romanian</a>

    <p id="paragraph">
      Bine ai venit pe site-ul meu!
    </p>

    <script type="text/javascript">
      localStorage.setItem("languageStored", "romanian");

      var language = {
        eng: {
          welcome: "Welcome to my website!"
        },
        ro: {
          welcome: "Bine ai venit pe site-ul meu!"
        }
      };

      window.onload = function() {
        let optEngl = document.getElementById('english');
        let optRo = document.getElementById('romanian');

        optEngl.onclick = function() {
          languageChange(this, "optEngl");
        }
        optRo.onclick = function() {
          languageChange(this, "optRo");
        }
      }

      function languageChange(e, obj) {
        let languageStored = localStorage.getItem("languageStored");
        if (languageStored != obj) {
          localStorage.setItem("languageStored", obj);
          if (languageStored.localeCompare("optEngl")) {
            document.getElementById('paragraph').textContent = language.eng.welcome;
          } else {
            document.getElementById('paragraph').textContent = language.ro.welcome;
          }
        }
      }

    </script>

  </body>

</html>

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

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