gpt4 book ai didi

javascript - jQuery + Javascript - 在匿名函数中访问对象字段

转载 作者:行者123 更新时间:2023-11-30 10:36:45 25 4
gpt4 key购买 nike

我不喜欢 JavaScript OOP,所以我创建了一个包含一些字段的对象,其中包含一些要调用的函数。

var test = {
questions: [],

addQuestion: function(questionTitle, possibleAnwsers)
{
// not really important
},

appendQuestionToHTML: function(question)
{
// not really important
},

makeQuestionFieldsEditable: function($questionNode)
{
$questionNode.find(".questionTitle").first(function(){this.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){this.changeTextOnClick($(this));});
},

changeTextOnClick: function($spanElement)
{
// not really important
}
};

makeQuestionFieldsEditable() 函数中的以下对象查找“.questionTitle”类节点,所有“.questionChoice”类节点都为它们调用另一个函数。问题是在匿名函数中使用 this 引用自身,而不是保存在字段 changeTextOnClick 上的函数。Javascript/JQuery 想要在不存在的 HTMLDivElement 上调用此函数。

有什么解决办法吗?

最佳答案

您可以使用对您的 this 变量的引用来实现这个技巧:

makeQuestionFieldsEditable: function($questionNode)
{
var that = this;
$questionNode.find(".questionTitle").first(function(){that.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){that.changeTextOnClick($(this));});
},

关于javascript - jQuery + Javascript - 在匿名函数中访问对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594356/

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