$(这个) 和这个。在同一个函数中

$(this) and this. in the same function

下面的代码将调用一个函数,将点击的名称添加到一个数组中。但是,$(this) 正在调用应用程序对象而不是单击的文本。我猜我不能在同一个函数中使用 $(this) 和 this 并期望 this 调用不同的东西。有替代解决方案吗?

var App = function () {
this.friends = [];
};

App.prototype.addFriend = function () {
name = $(this).text();
this.friends.push(name); 
}

var app = new App();

$(document).ready(function () {
$(document).on("click", ".user", function () {app.addFriend()});
}

将事件对象传递给函数并从中获取值

var App = function () {
this.friends = [];
};

App.prototype.addFriend = function (event) {
name = $(event).target.value;
this.friends.push(name); 
}

var app = new App();

$(document).ready(function () {
$(document).on("click", ".user", function (event) {app.addFriend(event)});
}

您可以将点击事件的目标元素作为参数传递给addFriend():

App.prototype.addFriend = function (item) {
name = $(item).text();
this.friends.push(name); 
}

var app = new App();

$(document).ready(function () {
$(document).on("click", ".user", function (event) {app.addFriend(event.target)});
}