2

I have the following interface for a baseball-draft oriented hobby project of mine that lets a team owner build a set of criteria to rank players on:

ranking_formula

Clicking the attributes will add that attribute to the list, give it an importance factor and a sort direction.

In Rails 2 and Rails 3 (with the prototype helpers) - I did this by having the following:

<div class="rankingvaluecloud">
  <ul> 
      <% @rankingattributes.each do |attributename| %>
        <li><%= add_ranking_attribute_link(attributename) %></li>
      <% end %>
  </ul>
</div>
<div id="rankingattributes">
</div>

Where "add_ranking_attribute_link(attributename)" is:

def add_ranking_attribute_link(attributename) 
  link_to_function attributename do |page| 
    page.insert_html :bottom, :rankingattributes, :partial => 'ranking_attribute', :locals => {:attributename => attributename }
  end
end

I'm converting this to jquery, but I'm not sure the best way to do it - mainly because of the loop involved. I can do this:

<div class="rankingvaluecloud">
  <ul> 
      <% @rankingattributes.each do |attributename| %>
        <li><%= link_to(attributename,'#',:class => 'attributeappend', :onclick => "$('#rankingattributes').append('#{escape_javascript(render(:partial => 'ranking_attribute',:locals => {:attributename => attributename}))}')") %></li>
      <% end %>
  </ul>
</div>
<div id="rankingattributes">
</div>

Which is basically just replacing the link_to_function. But is there a better way? The ujs way would have me doing something like:

$(".attributeappend).click(function() {
  $('#rankingattributes').append('#{escape_javascript(render(:partial => 'ranking_attribute',:locals => {:attributename => attributename}))}')
});

But that doesn't work out outside the loop because of the attributename handling. I honestly get a bit lost mixing in erb and javascript - and don't know a good way of passing attributename as a param to the javascript function to insert back into the render partial without a fragile cascade of debugging erb and javascript syntax errors, both of which are frustrating to debug.

There has to be a better way though (and I'm sure there's a better interface for this, suggestions welcome!).

4

1 回答 1

0

我会在视图中这样做:

link_to 'attributename','#',:class => 'attributeappend'

然后js的匹配位将是

$(".attributeappend").click(function() {
  $('#rankingattributes').append($('#template').html().replace(/toReplace/g, $(this).text());
  return false;
});

这假设您在 id 页面上有一个不可见元素template,例如

<div id="template">
 Attribute: toReplace
 ...

</div>

当您单击链接时,javascript 会触发。它从模板中获取 html 并将 toReplace 的所有实例替换为它从链接中提取的文本,并将其附加到具有 id 的元素ranking attributes

如果您希望链接中的文本与以这种方式替换的实际值不同,您可以在链接上添加具有正确值的数据属性。

于 2011-12-23T20:07:51.593 回答