在Rails中使用jQuery的新功能,并且无法为click或hover事件识别div。使用coffeescript,但编译看起来很好。在Chrome开发工具的元素窗口中div都很好看,但是我没有在控制台窗口中获得我的console.log。
我的_form.html.haml的一部分
.field
= f.label :question
= f.text_field :question
%p Click the plus sign to add answers.
.field#answerone
= f.label :answers
= f.text_field :answers
#plusanswer
= image_tag("plusWhite.png", :alt => "plus sign")
.actions
= f.submit 'Save'
CoffeeScript的:
$("#plusanswer").click ->
console.log("here we are")
$("#answerone").clone().appendto()
编译javascript:
(function() {
$("#plusanswer").click(function() {
console.log("here we are");
return $("#answerone").clone().appendto();
});
}).call(this);
我正在做image_tag的方式弄乱了吗?
答案 0 :(得分:3)
我相信塞尔吉奥的评论是正确的。如果你的JS出现在页面的标记之前,则选择器$(#plusanswer')
在该元素存在之前运行。您可以使用代码
console.log $('#pluganswer').length
要解决此问题,请将代码包装在jQuery的文档就绪包装器中,如下所示:
$ ->
# the rest of your code goes here
这看起来有点神奇,但这是它的工作原理:当你将一个函数传递给jQuery对象$
时,它只在document
的“就绪”事件触发后运行该函数。因此,再次假设您的代码在您的标记之前,您应该得到这种行为:
console.log $('#pluganswer').length # 0
$ ->
console.log $('#pluganswer').length # 1, because the page's markup is loaded