JavaScript function doesn't work when used inside onclick attribute

I have a simple HTML link in which I call the onClick JavaScript function and try to switch the resulting value. This does not work.

Here is my code:

function lang(language) { switch (language) { case "it-IT": alert("Italiano selezionato"); break; case "en-US": alert("English selected"); break; } } 
 <p><a href="#" onClick="lang('en-US');">English</a></p> <p><a href="#" onClick="lang('it-IT');">Italiano</a></p> 
+5
source share
3 answers

Do not use lang for the name of your function, the browser already uses it.

 function xlang(language) { switch (language) { case "it-IT": alert("Italiano selezionato"); break; case "en-US": alert("English selected"); break; } } 
 <p><a href="#" onClick="xlang('en-US');">English</a></p> <p><a href="#" onClick="xlang('it-IT');">Italiano</a></p> 
+12
source

The problem is here. Around onclick event handler is using with , which allows you to use all global attributes (including lang ). Therefore, he is trying to access the global lang property.

So change the function name to anything else but not attributes names

 <p><a href="#" onClick="alertLang('en-US');">English</a></p> <p><a href="#" onClick="alertLang('it-IT');">Italiano</a></p> <script> function alertLang(language) { switch (language) { case "it-IT": alert("Italiano selezionato"); break; case "en-US": alert("English selected"); break; } } </script> 

But it will work if you add it as an event handler in Javascript

 <p><a href="#">English</a></p> <script> function lang() { alert("English selected"); } document.querySelector('p').onclick = lang; </script> 
+2
source

When you assign JavaScript code to the onclick handler, it runs in a special area where the properties of this element are directly accessible, since they execute inside the with (element) { } block.

In your example, the lang variable corresponds to the lang attribute of the element. Other examples that lead to the same error include id , title , style and href . Think about it by running the following code:

 function lang() { } with(element) { lang("en-US"); // type error since lang resolves to element.lang // instead of the outer lang } 

You can simply specify your function:

 var MyFancyFunctions { lang: function { } }; 
 <a onclick="MyFancyFunctions.lang('en-US')">English</a> 

Or just remove the ambiguity:

 <a onclick="window.lang('en-US')">English</a> 

Literature:

internal raw handler

0
source

Source: https://habr.com/ru/post/1258846/


All Articles