Javascript 如何将参数传递给addEventListener侦听器函数?

Javascript 如何将参数传递给addEventListener侦听器函数?,javascript,dom,addeventlistener,Javascript,Dom,Addeventlistener,情况有点像- var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false); 问题是,someVar的值在addEventListener的侦听器函数中不可见,它可能被视为一个新变量。您编写的代码绝对没有问题。some_函数和someVar都应该可以访问,以防它们在匿名的上下文中可用 function() { som

情况有点像-

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

问题是,
someVar
的值在
addEventListener
的侦听器函数中不可见,它可能被视为一个新变量。

您编写的代码绝对没有问题。
some_函数
someVar
都应该可以访问,以防它们在匿名的上下文中可用

function() { some_function(someVar); } 
创建了

检查警报是否提供了您一直在寻找的值,确保它在匿名函数的范围内可访问(除非在调用
addEventListener
的旁边有更多代码在同一
someVar
变量上运行)


someVar
值只能在
some\u function()
上下文中访问,而不能从侦听器的上下文中访问。 如果您想在listener中使用它,您必须执行以下操作:

someObj.addEventListener("click",
                         function(){
                             var newVar = someVar;
                             some_function(someVar);
                         },
                         false);
并改用
newVar

另一种方法是从
some_function()
返回
someVar
值,以便在侦听器中进一步使用它(作为新的本地变量):


通过将函数声明为变量,可以添加和删除带有参数的EventListener

myaudio.addEventListener('end',funcName=function(){newSrc(myaudio)},false)

newSrc
是以myaudio为参数的方法
funcName
是函数名变量

您可以使用删除侦听器
myaudio.removeEventListener('ended',func,false)

也可以试试这些(IE8+Chrome,我不知道FF):

希望没有输入错误:-)

使用

   el.addEventListener('click',
    function(){
        // this will give you the id value 
        alert(this.id);    
    },
false);
如果您想将任何自定义值传递给这个匿名函数,那么最简单的方法就是

 // this will dynamically create property a property
 // you can create anything like el.<your  variable>
 el.myvalue = "hello world";
 el.addEventListener('click',
    function(){
        //this will show you the myvalue 
        alert(el.myvalue);
        // this will give you the id value 
        alert(this.id);    
    },
false);
//这将动态创建一个属性
//你可以创建任何类似el的东西。
el.myvalue=“你好,世界”;
el.addEventListener('单击',
函数(){
//这将显示myvalue
警报(el.myvalue);
//这将为您提供id值
警报(this.id);
},
假);

在我的项目中非常有效。希望这会有所帮助,为什么不直接从事件的target属性获取参数呢

例如:

var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
    some_function(arguments[0]);
}, false);
const someInput=document.querySelector('button');
someInput.addEventListener('click',myFunc,false);
someInput.myParam='这是我的参数';
函数myFunc(evt)
{
window.alert(evt.currentTarget.myParam);
}

Show parameter
这个问题很老了,但我想我应该使用ES5的
.bind()
-为后代提供一个替代方案。:)

请注意,您需要设置侦听器函数,将第一个参数设置为要传递到bind(另一个函数)的参数,第二个参数现在是事件(而不是第一个参数).

是一种将目标函数绑定到特定范围的方法,并且可以选择在目标函数中定义
对象

someObj.addEventListener("click", some_function.bind(this), false);
或者捕获一些词法范围,例如在循环中:

someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
最后,如果目标函数中不需要
参数:

someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);

// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);

您可以使用“bind”绑定所有必要的参数:

root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
通过这种方式,您将始终获得
事件
arg1
,以及传递给
myPrettyHandler
的其他内容


以下答案是正确的,但如果您使用yuicompressor压缩js文件,则以下代码在IE8中不起作用。(事实上,大多数美国人仍在使用IE8)

因此,我们可以按如下方式解决上述问题,它在所有浏览器中都可以正常工作

var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);
希望它对在生产环境中压缩js文件的人有用


祝你好运

所有函数中都有一个特殊变量:参数。您可以将参数作为匿名参数传递,并通过arguments变量(按顺序)访问它们

例如:

var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
    some_function(arguments[0]);
}, false);
还有另一种方法(这一种在循环内部工作):


以下代码对我(firefox)运行良好:


向eventListener的回调函数发送参数需要创建一个隔离函数并将参数传递给该隔离函数

someObj.addEventListener("click", some_function.bind(this), false);
这里有一个很好的小助手函数,你可以使用。基于上面的“hello world”示例。)

还需要维护对函数的引用,这样我们就可以干净地删除侦听器

// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running 
// within loops.
//
// The anonymous function returns a closure, that will be executed when 
// the event triggers. And since the arguments were captured, any vars 
// that were sent in will be unique to the function.

function addListenerWithArgs(elem, evt, func, vars){
    var f = function(ff, vv){
            return (function (){
                ff(vv);
            });
    }(func, vars);

    elem.addEventListener(evt, f);

    return f;
}

// Usage:

function doSomething(withThis){
    console.log("withThis", withThis);
}

// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");

// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);

一种方法是使用外部函数执行此操作:

elem.addEventListener('click', (function(numCopy) {
  return function() {
    alert(numCopy)
  };
})(num));
这种将匿名函数包装在括号中并立即调用的方法称为IIFE(立即调用的函数表达式)

您可以在中检查具有两个参数的示例


以下方法对我很有效。修改自

函数回调(theVar){
返回函数(){
theVar();
}
}
函数some_other_函数(){
document.body.innerHTML+=“成功了。”;
}
var someVar=一些其他函数;
document.getElementById('button').addEventListener('click',callback(someVar))

点击我!

当我在循环中使用它查找元素并向其中添加listner时,我陷入了这个困境。如果您在循环中使用它,那么这将非常有效

for (var i = 0; i < states_array.length; i++) {
     var link = document.getElementById('apply_'+states_array[i].state_id);
     link.my_id = i;
     link.addEventListener('click', function(e) {   
        alert(e.target.my_id);        
        some_function(states_array[e.target.my_id].css_url);
     });
}
for(var i=0;i
您可以通过javascript功能通过值(而不是引用)传递somevar,该功能称为:

或者您可以编写一个常见的wrap函数,例如
wrapEventCallback

function wrapEventCallback(callback){
    var args = Array.prototype.slice.call(arguments, 1);
    return function(e){
        callback.apply(this, args)
    }
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'
这里的
wrapEventCallback(func,var1,var2)
类似于:

func.bind(null, var1,var2)

这是一个相当古老的问题,但我今天也有同样的问题。最干净的溶液
// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running 
// within loops.
//
// The anonymous function returns a closure, that will be executed when 
// the event triggers. And since the arguments were captured, any vars 
// that were sent in will be unique to the function.

function addListenerWithArgs(elem, evt, func, vars){
    var f = function(ff, vv){
            return (function (){
                ff(vv);
            });
    }(func, vars);

    elem.addEventListener(evt, f);

    return f;
}

// Usage:

function doSomething(withThis){
    console.log("withThis", withThis);
}

// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");

// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);
    var EV = {
        ev: '',
        fn: '',
        elem: '',
        add: function () {
            this.elem.addEventListener(this.ev, this.fn, false);
        }
    };

    function cons() {
        console.log('some what');
    }

    EV.ev = 'click';
    EV.fn = cons;
    EV.elem = document.getElementById('body');
    EV.add();

//If you want to add one more listener for load event then simply add this two lines of code:

    EV.ev = 'load';
    EV.add();
elem.addEventListener('click', (function(numCopy) {
  return function() {
    alert(numCopy)
  };
})(num));
catimg.addEventListener('click', (function(c, i){
  return function() {
    c.meows++;
    i.textContent = c.name + '\'s meows are: ' + c.meows;
  }
})(cat, catmeows));
for (var i = 0; i < states_array.length; i++) {
     var link = document.getElementById('apply_'+states_array[i].state_id);
     link.my_id = i;
     link.addEventListener('click', function(e) {   
        alert(e.target.my_id);        
        some_function(states_array[e.target.my_id].css_url);
     });
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',function(someVar){
   return function(){func(someVar)}
}(someVar));
someVar='changed'
function wrapEventCallback(callback){
    var args = Array.prototype.slice.call(arguments, 1);
    return function(e){
        callback.apply(this, args)
    }
}
var someVar='origin';
func = function(v){
    console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'
func.bind(null, var1,var2)
someObj.addEventListener('click', some_function(someVar));

var some_function = function(someVar) {
    return function curried_func(e) {
        // do something here
    }
}
newElem.addEventListener('click', {
    handleEvent: function (event) {
        clickImg(parameter);
    }
});
// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);

// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);
someObject.addEventListener('event', () => myCallback(params));
    $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
    function save(data, keyword, name, comment, event) {
element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {

 //some action...

}
    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
 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;)
   }
function Name()
{

this.methodName = "Value"

}
someObj.setAttribute("onclick", "function(parameter)");
    window.addEventListener('click', (e) => functionHandler(e, ...args));