我在我正在开发的网站上安装了一个 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 方法之后的所有内容并将其应用到我的代码中,但也没有成功。
我还尝试了其他方法,例如调整上面的代码以动态创建按钮,然后使用附加/前置方法附加或前置它。这有效,但仅在附加到模态容器时有效,模态容器始终将按钮添加到容器外部。我没能在某些元素之后附加按钮,例如 #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' */
);
关于javascript - 无法将事件处理程序添加到带有 ID 的按钮中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636311/