我在 EcmaScript 6 类中使用 JQuery,并且我有一个事件函数,该函数在类的实例化时触发,并且该事件包含需要与 Class 交互的不同 JQuery 事件,因此我使用 .bind() 来实现那,除了一个事件之外,所有工作都正常,该事件由于某种原因用我通过 .bind(that) 方法传递的“that”覆盖了属于jquery元素“this”的 this ,这是我的代码(除了这个事件之外,一切都有效):
var that = this;
$(document).on('click', '[select-file]' , function(event) {
event.preventDefault();
console.log(this);
}.bind(that));
所以控制台日志给了我父类而不是jquery元素 这按预期工作:
$(document).on('click', '[open-file-dialoge]', function(event) {
event.preventDefault();
$('[file-dialoge]').modal('show');
if ($(this).attr('mitiupload') == 'false') {
// check if multiple upload is disabled
that.multiUpload = false;
$(this).removeAttr('multiple');
}
that.insertFiles();
}.bind(that));
请帮忙,我不明白这里发生了什么,尽管它们之间没有太大区别,但它没有按预期工作;(
最佳答案
Function#bind()
更改函数中 this
的上下文。如果您想要当前元素,可以使用 event.currentTarget
var that = {};
$(document).on('click', 'button', function(event) {
event.preventDefault();
var el = event.currentTarget;
console.log('this=', this);
console.log('el=', el)
}.bind(that));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Click me</button>
关于javascript - 绑定(bind)到jquery函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45354385/