如何使用接受属性的回调函数添加事件侦听器?

时间:2010-02-05 15:33:36

标签: javascript

还有,如何删除呢?

2 个答案:

答案 0 :(得分:1)

// we're in some internal scope here
var x = 10;
var fn = function( e ) {
    wrappedFunction( e, x );
}

//add
o.addEventListener( 'click', fn, false );

// create remover
var remover = function() {
    o.removeEventListener( 'click', fn, false );
}


//save the remover for later or return it - when it's called from whatever scope the event is removed
remover();

答案 1 :(得分:0)

当你说“属性”时,你的意思是参数/参数吗?

如果是这样,您可以动态分配一个接受参数的事件处理程序。在下面的示例中,参数testValue将传递给动态分配的事件处理程序:

<html>
<head>
<title>Test</title>
</head>
<body>

<input id="testInput" type="text"/>

<script type="text/javascript">
    var testValue = "Success.";
    document.getElementById("testInput").onkeydown = function() {
        test(testValue); }

    function test(testValue) {
        alert(testValue);
    }
</script>    
</body>
</html>

要删除事件处理程序,您可以将其分配给null

document.getElementById("testInput").onkeydown = null;