本文介绍了如何传递/转义使用javascript附加的事件处理程序的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 使用
setAttribute() ...)
。 - 事件处理程序传递一个动态读取的参数。
- 事件处理程序成功附件(通过
getAttribute(...)
但是,该处理程序不会触发。 b
$ b
下面的代码片段有什么问题?
< 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>
函数加载器(){
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>
解决方案
Tim的帖子帮助我弄清楚了虽然我的理解是经验的。
除了进行直接分配之外,还有一个
document.getElementById(...)。onMouseOver = stuff;
函数stuff(){//做契约};
代替
的document.getElementById(...)的setAttribute(...)。
显然,附加的事件处理程序可能不会接受任何参数。
我更改了我的处理程序签名以接受0个参数,它的工作原理!
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>
解决方案
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!
这篇关于如何传递/转义使用javascript附加的事件处理程序的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!