Built-in JS Vs callback syntax Internal JS callback syntax

The built-in JS callback syntax is as follows:

<h3 id="h3style" onMouseOver="changeColor();">     
      Rollover
</h3>

The JS internal response syntax is as follows:

<script>
     document.getElementById('h3style').onMouseOver = changeColor;
     function changeColor(){ } 
</script>

I understand that the first syntax is evaluated by the browser engine, and the second syntax is evaluated by the JS engine.

But why does the html attribute onMouseOvermatter as a function call (with parentheses) as opposed to the second approach? Why is the syntax of the html ( onMouseOver="changeColor;") attribute not allowed?

Note. It’s hard to remember two different syntaxes

+4
source share
3 answers

Let's start by looking at a clean version of js.

document.getElementById('h3style').onMouseOver = changeColor;
function changeColor(){ } 

- , . , - , , , ( ). , " javascript" , , " javascript". , :

elem.onMouseOver = 'changeColor();'; // technically legal but does nothing (just assigns a string)

javascript eval(), javascript. :

eval('changeColor();');

, DOM. - , - ( javascript). , - eval().

, html , , javascript, . , javascript.


, : " html syntax(onMouseOver="changeColor;") ?", . javascript:

onMouseOver = function(){
    eval('changeColor;');
}

.

+3

:

function onmouseover(event) {
  changeColor();
}

- changeColor

:

<html>
<body>

<h3 id="test1" onClick="test1();">
      test1
</h3>

<h3 id="test2">
      test2
</h3>

<script>
  function test1() {
    console.log('test1');
  }

  function test2() {
    console.log('test2');
  }

  document.getElementById('test2').onclick = test2;

  console.log(document.getElementById('test1').onclick);
  console.log(document.getElementById('test2').onclick);
</script>

</body>
</html>
Hide result
+1

( ).

  • IDL .

    JS, ( IDL),

    myelement.onmyevent = myfunction;
    

    , .

    . , , , JS, , - this.

  • HTML, JS setAttribute. , .

    myelement.setAttribute("onMyEvent", "some code here");
    

    . HTML- .

    , script, .

    , . , :

    • ,
    • , , ( ) ( ).

TL; DR: IDL , . , .

0

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


All Articles