如何为jQuery中动态创建的按钮点击函数传递参数?
问题原因
你用bind传递参数时,jQuery的bind方法第二个参数是事件数据,会被挂载到事件对象的data属性上,而不是直接作为函数参数传入,所以你的startGame函数拿到的language其实是事件对象,而非你传入的myParamValue。
方法一:箭头函数包装直接传参
修改GameButton类的append方法,用箭头函数包裹点击处理逻辑,直接把_attrs作为参数传给目标函数:
append() { $( '#gameContainer' ).append( '<img id="' + this._id + '" src="">'); $( '#' + this._id ).css( 'top', this._top + '%' ); $( '#' + this._id ).css( 'left', this._left + '%' ); // 用箭头函数包装,直接传递参数 $( '#' + this._id ).on( 'click', () => { this._buttonFunction(this._attrs); }); }
实例化按钮时,startGame函数可直接拿到传入的参数:
let startGame = function( language ) { console.log(language); // 输出 myParamValue // 你的业务代码 } let buttonStart = new GameButton( 'start', 43, 0, startGame, 'myParamValue' );
方法二:利用jQuery事件对象的data属性
如果想保留jQuery事件数据的传递方式,需要修改点击函数从事件对象中取参数:
- 修改
append方法的绑定代码:
append() { $( '#gameContainer' ).append( '<img id="' + this._id + '" src="">'); $( '#' + this._id ).css( 'top', this._top + '%' ); $( '#' + this._id ).css( 'left', this._left + '%' ); // 将参数存入事件数据 $( '#' + this._id ).on( 'click', { param: this._attrs }, this._buttonFunction ); }
- 修改
startGame函数接收参数的方式:
let startGame = function( event ) { const language = event.data.param; // 从事件对象中取出参数 console.log(language); // 输出 myParamValue // 你的业务代码 }
方法三:用Function.prototype.bind预绑定参数
在构造函数中直接用bind把参数绑定到目标函数上,后续正常绑定点击事件即可:
- 修改
GameButton的构造函数:
constructor ( id, width, height, buttonFunction, attrs ) { this._id = id; this._width = width; this._height = height; this._attrs = attrs; // 预绑定参数,null表示不改变函数的this指向 this._buttonFunction = buttonFunction.bind(null, attrs); }
append方法保持原来的绑定逻辑:
append() { $( '#gameContainer' ).append( '<img id="' + this._id + '" src="">'); $( '#' + this._id ).css( 'top', this._top + '%' ); $( '#' + this._id ).css( 'left', this._left + '%' ); $( '#' + this._id ).on( 'click', this._buttonFunction ); }
这种方式下,startGame函数依然可以直接接收参数,调用方式和第一种方法一致。
内容的提问来源于stack exchange,提问作者Jon Acedo
相关产品推荐
相关产品推荐

