Can't select link_to tag as jquery selector Rails

霸气de小男生 提交于 2019-12-14 03:36:11

问题


I am a beginner rails dev. I got this link_to tag with the class of "comments_link"

%h2= link_to pluralize(@recipe.comments.count, "Comment"), "#", class: "comments_link , btn btn-success"

Now, in application.js i wrote

$(document).ready(function(){
  $(".comments_link").click(function(){
    $(".section").toggle();
  });                               
})

The problem with this code, whatever element i choose for click event, it works. But when i use .comments_link class, it doesn't work. Why is this happening?

Anything but link_to tags work as event listener. Do i need to add some sort of code to it?

Btw i did the reverse just to try and it worked. When i click on the section, it toggles the link. But the link cant be event listener.

$(document).ready(function(){
  $(".section").click(function(){
    $(".comments_link").toggle();
  });                               
}); <-- this one worked. I cant use ".comments_link" as event listener.

回答1:


You have a comma in the class name which I assume would invalidate the class name. Check developer tools in order to inspect the element to see if .comment_link actually exists. If not, remove the comma and try again




回答2:


Assuming this is a problem with turbolinks, you can fix this by preventing the default action on the click in your event handler (which is a good idea anyway):

$(document).ready(function(){
  $(".comments_link").click(function(e){
    e.preventDefault();
    $(".section").toggle();
  });                               
})


来源:https://stackoverflow.com/questions/38465998/cant-select-link-to-tag-as-jquery-selector-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!