簡體   English   中英

為什么此代碼出現錯誤“Hi is not a function”

[英]Why this code got error "Hi is not a function"

當用戶點擊 on.step 時,jquery 將執行 hello function,效果很好。 你好 function 將調用 hi function => 我在這里遇到錯誤: Hi is not a function

jQuery(document).ready(function( $ ) {
    const form = {

        init: function() {
            $('.step').on('click', this.hello)
        },

        hello: function() {
          console.log('Index: ', $(this).index()); // I can get the right index
          this.hi(); // ERROR: Hi is not a function!
        },

        hi: function() {
            console.log('HI')
        },
    }

    form.init()
})

當我這樣放置代碼時,它工作正常

jQuery(document).ready(function( $ ) {
    const form = {

        init: function() {
            $('.step').on('click', this.hi) // Look here
        },

        hi: function() {
            console.log('HI')
        },
    }

    form.init()
})

你們能解釋一下為什么嗎?

你好不是 function

任何人都可以解釋為什么嗎?

在這段代碼中

    init: function() {
        $('.step').on('click', this.hello)
    },

    hello: function() {
      console.log('Index: ', $(this).index()); // I can get the right index
      this.hi(); // ERROR: Hi is not a function!
    },

您將form.hello設置為單擊事件的事件處理程序 在事件處理程序中, this是被單擊的元素,如:

  $("button").click(function() { console.log(this.id); }

按鈕(給定此代碼)將沒有.hi方法。

我們如何避免使用 Es6 或箭頭 function 進行綁定?

如果你不需要知道點擊了哪個按鈕,你可以在定義事件處理程序時使用箭頭 function :

    init: function() { 
        $('.step').on('click', () => this.hello())
    },

示例: https://jsfiddle.net/mcuh5awt/2/

理想情況下,您希望同時訪問按鈕表單 class,這有兩種可能,第一種是更改您定義 class 的方式,但保持您的操作方式,我們可以添加一個新屬性self存儲對其的引用......嗯......自我......

 jQuery(document).ready(function( $ ) { const form = { self: {}, init: function() { self = this; $('.step').on('click', self.hello) }, hello: function() { console.log('Index: ', $(this).index()); self.hi(); }, hi: function() { console.log('HI') }, } form.init() })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <button class='step' type='button'> Step 1 </button> <button class='step' type='button'> Step 2 </button> </div>

由於這成為您的 class 的公共財產,在這種情況下您可能更喜歡不同的名稱,例如form以匹配 class 名稱。

暫無
暫無

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

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