Why do we add "javascript:" before calling the function in HTML?

I have this code:

<html>
<head>
    <script>
      function myFunction() {
        document.getElementById("demo").innerHTML="Hello World";
      }
    </script>
</head>
<body>
    <button onclick="javascript:myFunction()">Click me</button>

    <p id="demo"></p>

</body>
</html>

if i change <button onclick="javascript:myFunction()">Click me</button>to

 <button onclick="myFunction()">Click me</button>

my code is working fine.

The difference between onclick="javascript:myFunction()"and onclick="myFunction()"?

+4
source share
1 answer

This is a pseudo-protocol javascript:that is lost. It is used when you have Javascript in the url, for example:

<a href="javascript:alert('hi')">Hi</a>

The event attribute does not support the protocol :javascript, so it does not work there. However, it becomes the same syntax as the label in Javascript, so the code actually still works, although the protocol is in the wrong place.

, , :javascript , , , .

+7

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


All Articles