在Jquery代码Rails中使用Link_to

时间:2015-05-27 12:25:49

标签: javascript jquery ruby-on-rails

我正在尝试在我的jquery代码中使用linkt_to<%= link_to 'address' , boat_path("'+boat_id+'") %>),但我认为由于连接问题,它无法正常工作。

这是我的Jquery代码;

<script>

    (function ( $ ) {

      $('#map-canvas').mapSearch({
        request_uri: 'locations/show.json', 
        initialPosition: [ <%= @initlat %> , <%= @initlng %> ],
        filters_form : '#filters',
        listing_template : function(listing){ 
          var pics = listing.pic.image.thumb.url
          var address = listing.loc.address
          var boat_id = listing.loc.boat_id
          console.log(boat_id) // works fine
                    return '<div class="listing">'
                      +     '<h3>'+ '<%= link_to 'address' , boat_path("'+boat_id+'") %>' + '</h3>' // HERE IS THE PROBLEM
                      +   '<div class="row">'
                      +        '<div class="col-sm-2">'
                      +         '<img src= "'+pics+'" >'
                      +          '</div>'
                      +        '<div class="col-sm-5">'
                      +           '<p><strong>Address : </strong>' + listing.address+ '</p>'
                      +               '<p>'+listing.boat.year+', '+listing.boat.model+' '+listing.boat.captained+'</p>'
                      +               '<p>Reg Year: ' + listing.boat.year+'</p>'
                      +          '</div>'
                      +        '<div class="col-sm-5">'
                      +         '<p><strong>demo:</strong> '+listing.address+'</p>'
                      +         '<p><strong>demo:</strong> '+listing.address+'</p>'
                      +          '</div>'
                      +   '</div>'
                      +  '</div>';

                  },
        marker_clusterer : true
      });
    }( jQuery ));

  </script>

首先,我无法获取地址,它通过放置字地址来渲染页面,而boat_id不起作用。该链接获得http://localhost:3000/boats/'+boat_id+'而非http://localhost:3000/boats/250。但是,当我对boat_id部分进行硬编码时,它可以工作。

那么,我该如何改变呢;

'<%= link_to 'address' , boat_path("'+boat_id+'") %>' to show address itself and the boat_id as number.

谢谢!

3 个答案:

答案 0 :(得分:1)

而不是ruby代码,编写

的html代码
"<a href='boats/"+boat_id+"'>Address</a>"

答案 1 :(得分:0)

boat_id是一个javascript变量 - 这意味着在浏览器中执行javascript代码之前,它不可用。

link_to是一个ruby / rails方法,这意味着它将在服务器上执行。

因此,在执行link_to方法时,您的boat_id var将无法使用。

没有办法解决这个问题 - 您将不得不使用link_to,并使用纯文本在javascript中手动生成您的网址/链接。

答案 2 :(得分:0)

让我们假设你想在元素中有一个链接说

<div class="test">
</div>

在div中添加链接的jQuery代码

var boat_id = 2;  
$('.test').html("<a href='path/" + boat_id.toString() + "'>boat</a>");

上面的jQuery代码将在div中创建一个链接。