简体   繁体   中英

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 />
  <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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM