开发者

Using link_to_function with anchor

I have view form like this:

<% @company.projects.each do |project| %>
<%= link_to_function project.title, "toggle_information_for('#{project.id}')" %>
<br /&g开发者_开发百科t;
  <div id="information_for_<%= project.id %>">
  <p><%= project.information %></p>
  <br/>
  </div>
<% end %>

And I have this jQuery function:

function toggle_information_for(project){
$("#information_for_"+project).toggle();
}

How can I make link_to like anchor?

For example:

If I click to project.title, then opening information about project by toggle_information_for function and url changed to /#project_id. How can I make it?


I'm not sure that I understand your question, but you're looking to call the toggle_information_for JS function, you need to write your link_to like this:

<%= link_to_function project.title, "javascript:toggle_information_for('#{project.id}')" %>

If you're looking to add the project ID to your URL, try:

function toggle_information_for(project){
    $('#information_for_' + project).toggle();
    location.hash = project;
}

Hopefully that helps. And while this works, I'd recommend getting rid of the direct JS call in the href of the link and add an event handler directly in your JS by writing your link_to like this:

<%= link_to_function project.title, "#information_for_#{project.id}" %>

And writing your JavaScript like this:

function toggle_information_for(e){
    $(e.target.href).toggle();
    location.hash = project;
}

$('#wrapper_div').delegate('click', 'a', toggle_information_for);


I would advise adding a class and then separating the jQuery logic from the html.

<% @company.projects.each do |project| %>
<div class="info_for" id="info_for_<%= project.id %>">
<%=project.title%>
<br />
  <div>
  <p><%= project.information %></p>
  <br/>
  </div>
</div>
<% end %>

And then some jQuery

$('.info_for').click(function(){
   $('div',this).toggle();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜