使用 on() jQuery 方法将 'this' 作为参数传递给事件处理程序
Pass 'this' as an argument to event handler using on() jQuery method
我动态添加带有 class .footprint
的元素到 DOM 并且需要向它们添加 click()
事件。我当前的代码如下所示:
$("#pcb").on("click", ".footprint", selectFootprint);
但是,selectFootprint(sender)
方法有一个参数,我想在其中传递 DOM 元素 (this)。
我该怎么做?
很明显,在on() jQuery 函数中- this
关键字代表被点击的元素,因此您可以随意调用该函数。
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
(来自分解).
或者在你的情况下:
function selectFootprint(){
console.log( $( this ).text() );
}
$("#pcb").on("click", ".footprint", selectFootprint);
几个解决方案(传递父上下文):
1) 使用 jquerys 数据参数:
$("#pcb").on("click", ".footprint", this, function(e){
console.log(this, e.data);//data is the parents this
});
2) 使用闭包
var sender = this;
$("#pcb").on("click", ".footprint", function(){
selectFootprint.call(this, sender);
});
或者如果您只想传递 .footprint
:
$("#pcb").on("click", ".footprint",function(){
selectFootprint(this);
});
不是直接使用 selectFootprint 作为回调,而是定义一个调用 selectFootprint 的新函数,并将 this 作为参数(事件监听器中的 this 总是指监听器附加到的 DOM 元素)
$(".footprint").on("click", function() {
selectFootprint(this);
});
我动态添加带有 class .footprint
的元素到 DOM 并且需要向它们添加 click()
事件。我当前的代码如下所示:
$("#pcb").on("click", ".footprint", selectFootprint);
但是,selectFootprint(sender)
方法有一个参数,我想在其中传递 DOM 元素 (this)。
我该怎么做?
很明显,在on() jQuery 函数中- this
关键字代表被点击的元素,因此您可以随意调用该函数。
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
(来自分解).
或者在你的情况下:
function selectFootprint(){
console.log( $( this ).text() );
}
$("#pcb").on("click", ".footprint", selectFootprint);
几个解决方案(传递父上下文):
1) 使用 jquerys 数据参数:
$("#pcb").on("click", ".footprint", this, function(e){
console.log(this, e.data);//data is the parents this
});
2) 使用闭包
var sender = this;
$("#pcb").on("click", ".footprint", function(){
selectFootprint.call(this, sender);
});
或者如果您只想传递 .footprint
:
$("#pcb").on("click", ".footprint",function(){
selectFootprint(this);
});
不是直接使用 selectFootprint 作为回调,而是定义一个调用 selectFootprint 的新函数,并将 this 作为参数(事件监听器中的 this 总是指监听器附加到的 DOM 元素)
$(".footprint").on("click", function() {
selectFootprint(this);
});