2009-09-24 74 views
0

在代码HTML +下面脚本,如何将参数传递给使用javascript附加的事件处理程序?

  • 事件处理程序页面加载使用setAttribute(...)后附接。
  • 事件hander传递一个动态读取的参数。
  • 的事件处理程序成功地连接(通过getAttribute(...)

验证然而,该处理不火。

什么是错的下面?

<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> 

回答

0

蒂姆的那篇文章帮我弄明白了;尽管我的理解是经验的。

除了作出直接转让

例如,

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

代替

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

显然,事件处理程序连接可能不接受任何参数。

我改变了我的处理程序签名以接受0个参数,它的工作原理!

+0

不,在非IE浏览器中,您的事件处理函数将传递一个事件对象,这可能非常有用。在IE中,你必须通过window.event访问事件。例如:el.onmouseover = function(evt){evt = evt || window.event;/*做事件对象* /}; – 2009-10-02 08:48:34

+0

Ty(+:那很有用 目前我们只是在浏览IE,尽管 – Everyone 2009-10-11 18:31:00

1

不要使用该代码段setAttribute在DOM节点上设置事件处理程序只需使用事件处理程序属性direct,并为其分配一个函数而不是字符串:

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

有两个问题 - - IIRC处理程序不一定是匿名函数; Y/N? - 传递的参数是否需要转义? – Everyone 2009-09-24 11:08:58

+0

正确,处理程序不一定是匿名函数。其次,我没有太在意这个问题的转义部分,但我认为这一点不再是问题? – 2009-09-24 12:02:13

相关问题