当用户单击.step时,jquery将执行hello函数,该函数可以正常工作。 hello函数将调用hi函数=>我在这里遇到错误:Hi不是函数
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()
})
你们能解释为什么吗?
答案 0 :(得分:1)
Hi不是函数
有人可以解释为什么吗?
在此代码中
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
设置为click事件的事件处理程序。在事件处理程序中,this
是被单击的元素,如:
$("button").click(function() { console.log(this.id); }
按钮(鉴于此代码)将没有.hi
方法。
如何避免使用Es6或箭头功能进行绑定?
如果您不需要知道单击了哪个按钮,则可以在定义事件处理程序时使用箭头功能:
init: function() {
$('.step').on('click', () => this.hello())
},
示例:https://jsfiddle.net/mcuh5awt/2/
理想情况下,您需要同时访问按钮和表单类,这可以通过两种方式实现,第一种是更改定义类的方式,但要保持一致完成此操作后,我们可以添加一个新属性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>
由于这成为您班级的公共财产,因此在这种情况下,您可能希望使用其他名称,例如form
来匹配班级名称。