How to pass/escape an argument to an event handler

2019-08-21 08:43发布

问题:

In the code HTML+Script below,

  • an event handler is attached after page load using setAttribute(...).
  • The event hander is passed an argument which is read dynamically too.
  • the event hander is attached successfully ( verified by a getAttribute(...)

However, the handler does not fire.

What is wrong with the snippet below?

<HTML>
 <BODY onload="loader();">
   <table>
        <tbody>
            <tr>
                <td id="myId">FirstColumn</td>
                <td id="otherId">SecondColumn</td>
                <td id="lastId">Balderdash</td>
            </tr>
        </tbody>
   </table>
 </BODY>
 <script language="javascript">
    function loader(){

    document.getElementById('myId').setAttribute('onmouseover','showMessage("'+document.getElementById('otherId').innerHTML+'");');
    alert(document.getElementById('myId').getAttribute('onmouseover'));

    document.getElementById('myId').setAttribute('onmouseout','alert(\"'+document.getElementById('otherId').innerHTML+'\");');
    alert(document.getElementById('myId').getAttribute('onmouseout'));
    document.getElementById('lastId').setAttribute('onmouseout','alert("hohoho");');

    alert(document.getElementById('lastId').getAttribute('onmouseout'));
    function showMessage( aMessage ){
        alert(aMessage);
    }
 </script>
</HTML>

回答1:

Do not use setAttribute to set event handlers on DOM nodes. Just use the event handler property direct, and assign it a function rather than a string:

document.getElementById('myId').onmouseover = function() {
  showMessage(document.getElementById('otherId').innerHTML);
};


回答2:

Tim's post up there helped me figure it out; albeit my understanding is empirical.

In addition to making a direct assignment

e.g.

document.getElementById(...).onMouseOver = stuff;
function stuff(){//do the Deed};

in lieu of

document.getElementById(...).setAttribute(...);

Apparently the event handler attached may not accept any argument.

I changed my handler signatures to accept 0 arguments, and it works!