简体   繁体   中英

Javascript with ERB tag

I have a website that has a grid with multiple posts on one page. I'm trying to write a javascript function that changes the html on a specific post on the page.

I have this inside my <% @posts.each do |post| %> <% @posts.each do |post| %> loop

<script type="text/javascript">
    var ids = '#<%= song.id %>';
    function tagInfo(tag) {
    $(ids).html(tag);
}
</script>

This is an onClick function. The only problem is, the function isn't getting the ID correctly. When I click on the button, nothing happens. If i change it ids variable to say "#5" it works on the fifth post. But when I use the erb tag it doesn't work.

When I inspect the page though, it the script looks like this

<script type="text/javascript">
var ids = '#5';
    function tagInfo(tag) {
        $(ids).html(tag);
    }
</script>

So it should be working... any suggestions. I've tried <%= raw song.id %> but that doesn't work.

Helper function with the onClick handler

module SongsHelper
    def tags(tag_list)
      markup = ""
      tag_list.each do |tag|
        markup += content_tag(:a, tag, :class => tag, :onClick => 'tagInfo("' + tag +'");')
      end
      raw(markup)
    end
end

Things are actually much simpler when you stop using inline javascript. That looks like a nightmare to debug or even to follow the application flow.

You need to consider that

jQuery makes it so simple to attach handlers and traverse the DOM that you don't need to hack it like its 1999.

So instead of this unholy mess you would use an event handler together with data attributes .

<div id="posts">
  <% @posts.each do |post| %>
    <article class="post">
      <!-- more stuff -->
      <button class="tryme" data-id="<%= post.id %>">Try Me</button>
    </acticle>
  <% end %>
<% end %>

We can then create an event handler:

$(document).ready(function(){
  $('.post .tryme').click(function(){
    alert("You clicked: " + $(this).data('id'));
  });
});

This example might not be exactly what you looking for but you get the general idea.

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