简单的 CoffeeScript 和 jQuery 事件的奇怪问题
该事件在通配符选择器上正常触发,但如果我为选择器使用特定 ID,则会失败。
这有效:
$("*").click ->
console.log "entered event."
$("#tellafriend").dialog
modal: true
buttons:
Ok: ->
$(this).dialog "close"
然而,这无效:
$("#tell-a-friend").click ->
console.log "entered event."
$("#tellafriend").dialog
modal: true
buttons:
Ok: ->
$(this).dialog "close"
我的相关 HTML:
<ul class="actions">
<li><a href="#">Home</a></li>
<li>|</li>
<li><a href="#" id="tell-a-friend">Tell a Friend</a></li>
</ul>
我是否在 CoffeeScript 中遗漏了某些内容才能使其正常工作?也许 jQuery 选择器在 CoffeeScript 中的格式不同?
这是我的应用程序提供的渲染的 Javascript(Rails 在提供页面时将 CoffeeScript 转换为 JS):
(function() {
$("#tell-a-friend").click(function() {
console.log("works");
return $("#tellafriend").dialog({
modal: true,
buttons: {
Ok: function() {
return $(this).dialog("close");
}
}
});
});
}).call(this);
The event fires well on a wildcard selector, but fails if I use a specific ID for the selector.
This works:
$("*").click ->
console.log "entered event."
$("#tellafriend").dialog
modal: true
buttons:
Ok: ->
$(this).dialog "close"
Yet, this doesn't:
$("#tell-a-friend").click ->
console.log "entered event."
$("#tellafriend").dialog
modal: true
buttons:
Ok: ->
$(this).dialog "close"
And my relevant HTML:
<ul class="actions">
<li><a href="#">Home</a></li>
<li>|</li>
<li><a href="#" id="tell-a-friend">Tell a Friend</a></li>
</ul>
Am I missing something in CoffeeScript for this to work? Maybe jQuery selectors are formatted differently in CoffeeScript?
This is the rendered Javascript that my application serves (Rails convert CoffeeScript to JS when serving the pages):
(function() {
$("#tell-a-friend").click(function() {
console.log("works");
return $("#tellafriend").dialog({
modal: true,
buttons: {
Ok: function() {
return $(this).dialog("close");
}
}
});
});
}).call(this);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是否有可能在 DOM 完全加载之前就执行了代码。尝试将其包装在文档就绪处理程序中,以便在 DOM 完全加载后应用所有单击处理程序。事实上,它可能只在 body 元素上执行,因为这是执行脚本时唯一可用的元素。
Is it possible that the code is being executed before the DOM is completely loaded. Try wrapping it in a document ready handler so that any click handlers are applied after the DOM is completely loaded. As it is, it may only be executing on the body element because that's the only element available at the time the script is executed.