How to pass/escape an argument to an event handler attached using javascript?

僤鯓⒐⒋嵵緔 提交于 2019-12-25 04:36:24

问题


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!



来源:https://stackoverflow.com/questions/1470948/how-to-pass-escape-an-argument-to-an-event-handler-attached-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!