2016-08-16 78 views
0

我有一個div,我希望它成爲其他頁面的鏈接。通常我們會這樣做link_to linkRails,爲javascript添加紅寶石參數

<% for post in @posts %> 
    <%= link_to "Post", post %> # -> or <%= link_to(post) %> 
<% end %> 

但我需要整個div與js的鏈接。所以,我做了:

<% for post in @posts %> 
    <div class="post-on-main-page-<%= div_count %>" > 
     <script> 
      $(".post-on-main-page-<%= div_count %>").click(function(){ 
       window.location.href = "<%= link_to(post) %>"; 
       }); 
     </script> 
    </div> 
<% end %> 

但我沒有工作。

我需要window.location.href = "<%= link_to(post) %>";其中post是一個參數,給我一個該帖子的鏈接。

那麼我如何才能使這個工作?

+0

爲什麼不把數據屬性添加到'div'並使用該值來重定向? –

+0

試試這個'window.location.href =「#{link_to(post)}」; –

+0

@BrenoPerucchi沒有那麼壞 – naomik

回答

1

link_to會生成一個完整的<a>元素

您應該使用post_path(post)post_url(post),而是如果你只想路徑或URL

+0

謝謝post_url(post)爲我工作。 –

0

您可以通過一個blocklink_to幫手像

<% @posts.each do |post| %> 
    <%= link_to post do %> 
    <div class="post-on-main-page"> 
    <!-- Fill in your content --> 
    </div> 
    <% end %> 
<% end %> 

這將生成一個鏈接到posts#show頁面的div。

+0

是的,我意識到這一點。但這對我來說是不好的決定。 –