情况有点像
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。
情况有点像
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。
当前回答
为什么不直接从事件的目标属性获取参数呢?
例子:
const someInput = document.querySelector('button'); someInput。addEventListener('click', myFunc, false); someInput。myParam = '这是我的参数'; 函数myFunc (evt) { window.alert (evt.currentTarget.myParam); } <button class="input">显示参数</button>
JavaScript是一种面向原型的语言,记住!
其他回答
你需要:
newElem.addEventListener('click', {
handleEvent: function (event) {
clickImg(parameter);
}
});
可能不是最优的,但对于那些不精通js的人来说已经足够简单了。将调用addEventListener的函数放到它自己的函数中。通过这种方式,传递给它的任何函数值都保持自己的作用域,并且您可以尽可能多地迭代该函数。
示例我与文件读取,因为我需要捕捉和渲染图像和文件名的预览。在使用多文件上传类型时,我花了一段时间来避免异步问题。尽管上传了不同的文件,我还是会意外地在所有渲染中看到相同的“名称”。
最初,所有的readFile()函数都在readFiles()函数中。这导致了异步作用域问题。
function readFiles(input) {
if (input.files) {
for(i=0;i<input.files.length;i++) {
var filename = input.files[i].name;
if ( /\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {
readFile(input.files[i],filename);
}
}
}
} //end readFiles
function readFile(file,filename) {
var reader = new FileReader();
reader.addEventListener("load", function() { alert(filename);}, false);
reader.readAsDataURL(file);
} //end readFile
您编写的代码绝对没有任何问题。some_function和someVar都应该是可访问的,以防它们在匿名的上下文中可用
function() { some_function(someVar); }
被创建。
检查警报是否为您提供了您一直在寻找的值,确保它可以在匿名函数的作用域内访问(除非您在addEventListener调用旁边有更多操作相同someVar变量的代码)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
2019年,很多api发生了变化,最好的答案不再有效,没有修复错误。
分享一些工作代码。
受到以上所有答案的启发。
button_element = document.getElementById('your-button')
button_element.setAttribute('your-parameter-name',your-parameter-value);
button_element.addEventListener('click', your_function);
function your_function(event)
{
//when click print the parameter value
console.log(event.currentTarget.attributes.your-parameter-name.value;)
}
如果以后想要删除事件侦听器,那么创建对curry函数的引用是一个不错的选择。
在下面的代码中,我将说明我的意思。
// This is the curry function. We return a new function with the signature of what the click-listener expects
const handleClick = (foo, bar) => (clickEvent) => {
console.log('we get our custom input', foo, bar);
console.log('we get the click event too', clickEvent);
}
// We need to store a reference to the listener, making sure we are removing the correct reference later
const myListener = handleClick('foo', 'bar'); // Remember that we now return the actual event-handler
const btn = document.getElementById('btn'); // find the element to attach the listener to
btn.addEventListener('click', myListener);
// remove the event listener like this by using our reference
btn.removeEventListener('click', myListener);
下面是CodePen上的一个工作示例