用()赋值.onmousedown时,函数会在赋值时运行
Assigning .onmousedown with () runs the function when assigned , work arounds
如果我这样做:
image[i].onmousedown = whatever;
它将工作得很好,并在点击时运行whatever()函数。但是,如果我做以下操作:
image[i].onmousedown = whatever( name, what, when, where, how );
赋值属性时会运行函数。假设我创建了30张图片并想给它们所有的onmousedown函数,它会在加载时运行这个函数30次因为我在后面添加了()但是我要怎么给函数分配我想要的属性呢?
是使函数运行函数的唯一方法吗?所以输入
image[i].onmousedown = whatever;
function whatever() {
anotherWhatever( this, name, what, when, where, how );
}
我还必须分配一个新的值'这个'似乎?你们有什么建议或者请告诉我你们有更好的方法。提前感谢您的帮助
您可以使用ecmaScript5 bind函数来绑定上下文并设置要传入的参数。
image[i].onmousedown = whatever.bind(this, name, what, when, where, how );
这里的 this
将是绑定事件的当前上下文。如果你想获得元素本身的上下文,那么:
image[i].onmousedown = whatever.bind(image[i], name, what, when, where, how );
如MDN中所述,您可以将此脚本放在您的js中以获得旧浏览器的支持。
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
您需要将其封装在一个匿名函数中:
image[i].onmousedown = function () { whatever.call(this, name, what, when, where, how ); };
相关文章:
- Javascript变量赋值|
- 无法为打字稿字典赋值
- Javascript-根据赋值顺序,按键合并对象数组
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何通过json对象数组为嵌套对象赋值
- 赋值后的回调函数
- ||(OR)运算符如何在赋值中工作
- 可以使用属性赋值实现多个函数
- 将ECMAScript 6析构函数赋值(ES2015)重构为旧版本的javascript
- 如何在javascript中为全局变量赋值
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- JavaScript:在嵌套循环中为数组赋值
- 未设置变量的赋值| jQuery的作用是什么
- Javascript赋值运算符的奇怪行为
- onchange赋值的Javascript位置
- Javascript值未定义,函数在赋值后运行
- 如何在网站中为JS变量赋值,取决于它是否's正在本地运行或正在生产中
- 为函数赋值并在单独的按钮jquery上运行
- 用()赋值.onmousedown时,函数会在赋值时运行
- 将函数赋值给变量并运行它自己