gpt4 book ai didi

javascript - 访问单击的特定元素

转载 作者:行者123 更新时间:2023-11-30 08:29:24 25 4
gpt4 key购买 nike

我有以下方法

PMm.test = function (){
....plenty of code....

$('.element',this.page).click(function(e){
e.preventDefault();
var self = $(this);
console.log(self);
this.load(someoptions)
}.bind(this));

...plenty of code....

}

PMm.test.prototype.load = function(options){
...some code
}

console.log(self)时,它返回方法PMm.test。如果 $(this) 是我声明事件的整个函数范围,我如何访问单击的元素?知道我还需要调用稍后声明的 .load() 方法。

最佳答案

我认为最好将上下文存储在变量中,然后在回调中使用闭包访问它。这会导致代码更具可读性。

PMm.test = function (){
....plenty of code....
// Store the context in a variable.
var that = this;
$('.element',this.page).click(function(e){
e.preventDefault();
// this here references the DOM element (as expected)
var self = $(this);
console.log(self);
// you can access your methods through that.
that.load(someoptions)
});

...plenty of code....

}

PMm.test.prototype.load = function(options){
...some code
}

希望对您有所帮助。

关于javascript - 访问单击的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40180081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com