使用参数获取函数中的事件对象

时间:2014-05-05 20:50:06

标签: javascript

所以当你专注于某个元素时,我会在我的页面上添加一个keydown监听器,但是当你不在这个元素上时我想删除它。这工作正常,但我找不到将事件对象(e.preventDefault()所需)传递给此函数的方法。以下是我的代码的相关摘要:

// Named function for keydown listener (I need to pass the line 
// and layer objects into the function)
function keydownListener(line, layer) {
    e.preventDefault();
    // ... using the line and layer for various things ...
}

// adds event listener when you click on specific element
some_element.addEventListener('click', function() {(
    window.addEventListener('keydown', keydownListener(line, layer));
});

// removes event listener when you click on anywhere else (not real code. just to 
// demonstrate the idea)
anything_else.addEventListener('click', function() {
    window.removeEventListener('keydown', keydownListener);
});

是否无法将事件对象传递给具有其他参数的函数?

2 个答案:

答案 0 :(得分:1)

事件监听器函数接收event作为其第一个参数,尽管有些浏览器将此作为全局变量:

foo.addEventListener("click", function(event) {
    event = event || window.event;
    callOtherFunction(event, arg1, arg2);
});

答案 1 :(得分:1)

当触发click事件时,您可以尝试将事件传递给keydownListener

function handler(e)
    keydownListener(line, layer, e)
};

// adds event listener when you click on specific element
some_element.addEventListener('click', function() {
    window.addEventListener('keydown', handler)
});


// Named function for keydown listener (I need to pass the line 
// and layer objects into the function)
function keydownListener(line, layer, e) {
    e.preventDefault();
    // ... using the line and layer for various things ...
}