如何将局部变量值从函数传递给addEventListener函数?

时间:2017-11-22 21:50:23

标签: javascript

如何将局部变量值从函数传递给addEventListener函数?

以下是代码(JavaScript),

  d3.keys(__.dimensions).forEach(function(k) {
    if (!__.dimensions[k].yscale || __.dimensions[k].yscale){
      __.dimensions[k].yscale = defaultScales[__.dimensions[k].type](k);
    }
  });

如何将函数f()中的变量x值传递给addEventListener中的函数g()?

2 个答案:

答案 0 :(得分:2)

您可以尝试以下内容:

function f(){

   var x = new Audio('Audio URL')
   var divID = document.getElementById('id of a div');

   if(divID){
      divID.addEventListener(webkitAnimationEnd, () => g(x));
      divID.addEventListener(animationend, () => g(x));
  }
}


function g(x){
    //Code that uses variable x value and functions i.e x.pause() or x.play()
}

或者,如果您需要ES5支持,divID.addEventListener(webkitAnimationEnd, function() { g(x); });

答案 1 :(得分:1)

可能你会想要用一个闭包来做这件事:

function f(){

   var x = new Audio('Audio URL')
   var divID = document.getElementById('id of a div');

   if(divID){
      divID.addEventListener(webkitAnimationEnd, makeG(x));
      divID.addEventListener(animationend, makeG(x));
  }
}

function makeG(x) {
    return function() {
        //Code that uses variable x value and functions i.e x.pause() or x.play()
    }
}