我正在使用名为 sumoselect.js
的第三方 Jquery 插件在我的项目中。
在其中,一旦渲染了我的选择框,我就附加了一个带有 anchor 标记的 div 元素,并希望处理点击事件。
我做了类似的事情:
//## Create New Application Specific code
createNew: function () {
var O = this;
O.optDiv.append($('<ul class="form-control"><li><div style="margin-top:4px;"><a class="ispicon ispicon_plus" style="padding-left:12px;cursor:pointer;" data-toggle="modal" data-target="#addgroup" title="Create New"> Create New</a></div></li></ul>').on('click', handleClick));
},
handleClick: function () {
alert("Oh My");
},
但它说handleClick
未定义。
甚至将函数放在 createNew
之上抛出同样的错误。
我错过了什么?
最佳答案
handleClick
是调用它的对象内的一个函数,因此您应该将其更改为 this.handleClick
。下面的例子:
//## Create New Application Specific code
var foo = {
createNew: function () {
$('body').append($('<ul class="form-control"><li><div style="margin-top:4px;"><a class="ispicon ispicon_plus" style="padding-left:12px;cursor:pointer;" data-toggle="modal" data-target="#addgroup" title="Create New"> Create New</a></div></li></ul>').on('click', this.handleClick));
},
handleClick: function () {
alert("Oh My");
}
}
foo.createNew();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
在上面的代码片段中,您还可以使用 foo.handleClick
而不是 this.handleClick
。如果 this
实际上指的是其他内容(例如,在事件中),这会很方便。或者作为我最喜欢的 Ben Halpern 引言之一:
Sometimes when I'm writing Javascript I want to throw up my hands and say "this is bullshit!" but I can never remember what "this" refers to
关于javascript - JQuery 函数 fn() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298817/