开发者

How to add an event listener with a callback function that accepts attributes?

And also, how to remov开发者_如何学编程e it then?


// 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();


When you say "attributes", do you mean arguments/parameters?

If so, you can dynamically assign an event handler that does accept arguments. In the example below, the argument testValue is passed to the dynamically assigned event handler:

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

To remove the event handler, you can assign it to null:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜