gpt4 book ai didi

javascript - 从点击绑定(bind)调用方法

转载 作者:行者123 更新时间:2023-12-03 11:45:41 26 4
gpt4 key购买 nike

我有这个 fiddle :http://jsfiddle.net/jj258ykp/2/

对于 BTN2 和 BTN3,我在单击时看到警报,但在 BTN1 上没有看到警报,我希望看到它。

这是 CoffeeScript :

class A

method: ->
alert "method"

method2: ->
alert "method2"

@method3: ->
alert "method3"

setup: ->
$('button#btn').click( (event) ->
@method()
)
$('button#btn3').click( (event) ->
A.method3()
)



$ ->
a = new A
a.setup()

$('button#btn2').click( (event) ->
a.method2()
)

这是我的 HTML:

<button id = "btn">BTN1</button>
<button id = "btn2">BTN2</button>
<button id = "btn3">BTN3</button>

最佳答案

您正在尝试引用 this.method()(coffeescript 中的 @ 表示 this)。

由于调用位于点击处理程序的范围内,因此 this.method 将不存在。您需要通过实例化 A 或将 method 设置为成员变量(如 method3)来访问它:

  setup: -> 
$('button#btn').click( (event) ->
new A().method();
)

或者:

A
@method: ->
alert "method"

setup: ->
$('button#btn').click( (event) ->
A.method();
)

关于javascript - 从点击绑定(bind)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063845/

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