gpt4 book ai didi

javascript - 在带参数的函数中获取事件对象

转载 作者:行者123 更新时间:2023-12-02 17:26:17 26 4
gpt4 key购买 nike

因此,当您专注于某个元素时,我会在页面上添加一个 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);
});

有没有办法将事件对象传递给带有其他参数的函数?

最佳答案

您可以尝试在点击事件触发时将事件传递给 keydown 监听器

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

关于javascript - 在带参数的函数中获取事件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23481618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com