JQuery函数fn()没有定义

JQuery function fn() is not defined

本文关键字:定义 函数 fn JQuery      更新时间:2023-09-26

我在我的项目中使用第三方Jquery插件sumoselect.js

在它的内部,一旦我的选择框被渲染,我添加了一个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的一句话:

有时候,当我写Javascript的时候,我想把我的手和说"这是扯淡!"但我永远记不住"this"指的是什么