可以't将事件处理程序添加到ID为的按钮中

Can't Add Event Handler Into Button With ID

本文关键字:ID 按钮 添加 程序 事件处理 可以      更新时间:2024-02-10

我在一个正在开发的网站上安装了一个jQuery插件。当点击某个图像时,该插件会在网站上添加一个模态对话。我想在这个模式中添加第二个按钮,以关闭窗口,除了已经关闭的按钮之外,我通过在HTML中为按钮创建一个div来实现这一点。注意,模态的内容是在插件的内容变量中设置的,所以看起来像这样:

content: '<p>Want to get in touch? Drop us an email at:</p><br/>   
         <p><input type="text" id="inset" name="inset"     
         value="shoesfromlastnight@gmail.com"       
         onClick="javascript:this.focus();this.select();"  
         readonly="readonly" size="30"/></p> <br/> 
         <span id="appendto"><p>We look forward to hearing from you!</p></span> 
         <div type="button" id="crmbutton">Okay</div>' 

其中#crmbutton是我想用作按钮的div。不过,出于某种原因,我在将事件处理程序设置为在那里创建的按钮以使其关闭模态时遇到了问题。这听起来很简单,但由于某种原因,当我这样做时不会起作用:

$("#crmbutton").click(function() {     
this.close();
});

虽然我找不到任何文档,但我在这里使用的close()方法与插件自己的X按钮用于关闭模态的方法完全相同。值得一提的是,这是该按钮的代码,首先创建关闭按钮,然后使用.on方法,在点击时关闭模态:

this.closeButton = jQuery('<div/>', {'class': 'jBox-closeButton jBox-noDrag'}).on('touchend click', function(ev) { this.isOpen && this.close({ignoreDelay: true}); }.bind(this));

我还复制了.on方法之后的所有内容,并将其应用到我的代码中,但也没有成功。

我还尝试了其他方法,比如调整上面的代码以动态创建按钮,然后使用append/prepend方法对其进行附加或预处理。这是有效的,但只有在附加到模态的容器时才有效,该容器总是在容器外部添加按钮。我没有在某些元素后面添加按钮,比如#appendto——按钮就是不会被添加。

有人知道我在哪里会出错吗?这是我第一次使用jQuery,这让我沮丧不已。谢谢

问题是因为您没有在正确的范围内调用close方法。在事件侦听器中,"this"指向按钮。但是在您看到的代码中,'this'已通过.bind()方法更改为另一个作用域。

$("#crmbutton").click(function() {     
    /* 'this' points to the element #crmbutton, which doesn't have a close method */
    this.close(); 
});

在示例代码中,请查看使用.bind()方法的底部。

this.closeButton = jQuery(
    '<div/>', 
    {
        'class': 'jBox-closeButton jBox-noDrag'
    }
).on(
    'touchend click', 
    function(ev) {
        this.isOpen && this.close({ignoreDelay: true}); 
    }.bind(this) /* The scope is being set to another 'this' */
);

关于.bind()方法的文档