2016-09-15 56 views

回答

1

你可以做的添加使用.bind()自定义参数n个。这将是可作为申报的顺序.bind()

function myCallback(customArg, e) { 
... 
} 

window.addEventListener("message", myCallback.bind(this, customArg), false); 

function myCallback(customArg1,customArg2,customArg3,customArg4, e) { 
 
    alert(customArg1 + " " + customArg2 + " " + customArg3 + " " + customArg4) 
 
} 
 
$('button').click(myCallback.bind(this, 'hello', 'there', 'custom', 'args'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button>Click Me!</button>

0

使用封闭。它会捕获变量并将其保留在处理函数的作用域中。

function handler_factory(myVar) { 
    function handler(e) { 
     e.preventDefault(); 
     console.log(myVar); 
    } 

    return handler; 
} 

addEventListener("message", hander_factory("value of myVar")); 
0

您可以这样做 - 在回调函数中调用您的自定义函数。

window.addEventListener("message", function(e){ customFunction(e,variable) }); 
0

你可以做类似的事情,添加额外的参数甚至参数与对象是非常简单的。

var element = document.querySelector('input'); 
 
element.addEventListener('click', handle_parameter, false); 
 
element.customParam = 'Custom Param'; 
 

 
var object = {}; 
 
object.name = "Chris"; 
 
object.surname = "Beckett"; 
 

 
element.customParam2 = object; 
 

 
function handle_parameter(evt){ 
 
    document.getElementById("param1").innerHTML = evt.target.customParam; 
 
    document.getElementById("param2").innerHTML = evt.target.customParam2.name + " " + evt.target.customParam2.surname; 
 
}
<input type="button" value="test" /> 
 

 
<p id="param1"></p> 
 
<p id="param2"></p>

1

可以使用bind功能

document.getElementById('btn').addEventListener('click', add.bind(this,10,11)); 

function add(a,b){ 
    console.log(a,b) 
} 
-1

写下面的代码在你的脚本

var proxy = function (method, scope) { 
      var aArgs = Array.prototype.slice.call(arguments, 2); 
      return function() { 
       return method.apply(scope, Array.prototype.slice.call(arguments, 0).concat(aArgs)); 
      }; 
    } 

,并调用事件侦听器。在下面的代码,你可以使用这不过是你的实例或范围

window.addEventListener( “信息”,代理(YOURFUNCTIONNAME,这一点,ARG1,ARG2,ARG3));