Ruby/Rails + jQuery - Naming a variable jQuery selector in rails
I'm using Ruby/Rails to dynamically create a div and button through a loop, and I would like to know how do you name the element so jquery know which selector to apply the effect.
I have some simple ruby/html that creates several panels with photos in them and a button that runs some ajax in the background and then changes the color of the panel through the jQuery animate effect (I took out the remote calls in the link for brevity)开发者_运维问答
<% for photo in @photos %>
<div id="panel" style="background-color: #FFF;">
.....Text......
<%= link_to "Select", select_photo_path(photo), :class => "button" %>
</div>
<br />
<% end %>
and the jQuery looks like
<script>
$(document).ready(function(){
$(".button").click(function () {
$("#panel").animate({ backgroundColor: "#006600" }, 500);
});
});
</script>
So the problem is every time I click on of the buttons all the panels change color rather of the specific panel referenced in the for loop. I'm assuming this is because all the panels have the same id.
So how do I set the (class/id) of the buttons and panels so that the button1 .click event effects panel1 and button2 only works on panel2, etc, etc????
I'm pretty new to javascript right now.
Don't reference panel, but rather reference this.parent()
. this
in this case should be the button itself, where the parent()
will return the parent object. You should then animate that:
this.parent().animate({ backgroundColor: "#006600" }, 500);
You can use the [link_to_function] (http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#M001756) and define a custom function in Jquery and call it with
this.animate().
精彩评论