问题
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