簡體   English   中英

jQuery + Javascript - 訪問匿名函數中的對象字段

[英]jQuery + Javascript - accessing object fields in anonymous function

我沒有進入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”-class節點,並且所有“.questionChoice”類節點都為它們調用另一個函數。 問題是在匿名函數中使用它引用自身,而不是在字段changeTextOnClick上保存的函數。 Javascript / JQuery想要在HTMLDivElement上調用此函數,該函數不存在。

有什么解決方案嗎?

你可以使用對this變量的引用來做到this

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

我認為您需要做的就是將'this'更改為'test'(您為此對象指定的變量)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM