javascript - JQuery 函数 fn() 未定义

标签 javascript jquery html

我正在使用名为 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/

相关文章:

javascript - 如何在Python中将JS null写入文件而不是 'null'作为字符串

javascript - angular-bootstrap typeahead 使用 $http

javascript - 将 ASP.NET MVC Web 应用程序从 http 转换为 https

html - 缩放时保持内容居中

javascript - 源代码中 CSS 段和 JS 函数放置顺序的权衡

javascript - 在 html 中将数据从头部传递到 body 以引导一个 Angular 应用程序

javascript - 拖放后 TinyMCE 编辑器内容丢失

javascript - Razor:在标签内添加 @if - 然后设置属性

jQuery onclick 消失位于的 div

javascript - 如何识别滚动到的 View div 部分?