2012-05-01 67 views
0

我有一个像块:如何在没有“link_to”类助手的情况下调用ajax?

 - competitors.each do |competitor| 
     %dl 
      %dt 
      ... 
      %dd 
      %span{:id => "#{competitor['watchers']}"}= "#{((competitor['watchers']*100.0)/30000).round.to_f}%" 

注意,它产生DINAMIC CSS ID,一个每个块clicle,resoulting HTML是不同的DD列表 - >跨度 - >身份证号码:

<dl> 
    <dt> 
    ... 
    <dd> 
     <span id="774">93.0%</span> 
    </dd> 
    </dt> 
</dl> 
<dl> 
    <dt> 
    ... 
    <dd> 
     <span id="13774">46.0%</span> 
    </dd> 
    </dt> 
</dl> 

我想 “dinamically” 准 “自定义CSS代码段”,对不同的CSS的IDS(#13774#774),是这样的:

:javascript 
    $("##{competitor['watchers']}").css({ width: "#{((competitor['watchers']*100)/30000)}px" }); 

我怎么能叫AJAX(Rails中3.2.3':remote => true')没有link_to类助手?

,直到如今我试着刚刚从内部块调用JS一样:

 - competitors.each do |competitor| 
     :javascript 
      $("##{competitor['watchers']}").css({ width: "#{((competitor['watchers']*100)/30000)}px" }); 
     %dl 
      %dt 
      ... 
      %dd 
      %span{:id => "#{competitor['watchers']}"}= "#{((competitor['watchers']*100.0)/30000).round.to_f}%" 

,但它不工作,代码永远不会注入到DOM。

+0

你可以在link_to中使用:remote => true选项吗? –

回答

1

它看起来像你想表现出一定的条形图,在那种情况下,我建议如下(我假设你正在使用jQuery因为这是发生了什么标签):

更改块添加一个独特的类到每个跨度。这给你以后的风格好处。

%dd 
     %span{:id => "#{competitor['watchers']}", :class => "progress-bar"}= "#{((competitor['watchers']*100.0)/30000).round.to_f}%" 

那么你应该能够使用一些jQuery的页面的底部,选择每一个,做它的一些基本的数学:

$('span.progress-bar').each(function(index,element){ 
    var num = $(element).attr('id'); // get element id 
    var width = parseInt(num * 100/30000); // do your math, then get the integer value for width 
    $(element).css('width',width+'px'); // set width 
} 

我知道你要找的阿贾克斯,但除非我错过了一些东西,这应该接近于解决你记录的问题。

+0

对不起,Luca,你把html里面的html.erb页面,还是你把它添加到rails代码?我会将它添加到html.erb页面的底部,因为它会在浏览器看到它时立即运行,并且在它可以工作之前需要页面上的所有元素。这有帮助吗? – MaddHacker

+0

你也不需要这个在你的竞争对手。每个循环,你想要它之后。 – MaddHacker

+0

我已经把js放在了html.haml的底部,并且把js从竞争对手那里扔掉了,但是仍然错过了一些东西......我看不到“html宽度+'px'”成html/css结果页面...为了正确,我期望在js动作后看到 46.0%,而我只看到 46.0%

相关问题