weixin_33695450 2016-03-20 00:39 采纳率: 0%
浏览 55

Javascript和Ajax调用

I have a couple questions about loading javascript after an ajax call.

So I'm using ruby on rails and I have different pages loaded through ajax calls (I do this because I have an audio player that I want to keep playing as pages reload).

The problem is, when I change pages with ajax, the javascript doesnt reload (or work) on the new page.

For example, I have a grid system that sets the height of the grid image based on the width with javascript. The script doesnt work unless I reload the page or I put the script in a script tag at the bottom of the html file.

Is there any way to reload the javascript? I've tried location.reload() but that just refreshes the page and defeats the whole purpose. Thank you!

Here is an example:

show.js.erb

$('#results').html("<%= escape_javascript(render partial: 'songs/showcard', locals: { song: @song }) %>");

songs_controller

  def show
    respond_to do |format|
      format.js
      format.html
    end
  end

link to show page

<%= link_to song, remote: true do %><%= song.title %><% end %>

Here is the cardSize function I'm loading a in file called cardSize.js

$(document).ready(function cardSize () {
  var cardWidth = $('.card-image').width();
  $('.card-image').css({
    'height': cardWidth + 'px'
  });
});
  • 写回答

2条回答 默认 最新

  • weixin_33739523 2016-03-20 00:53
    关注

    In the UJS file show.js.erb you need to invoke the global functions that control the view / grid.

    For example, if the global method for controlling the height etc. is implement_grid(), then, the file should look like:

    $('#results').html("<%= escape_javascript(render partial: 'songs/showcard', locals: { song: @song }) %>");
    implement_grid();
    

    Items added to the DOM dynamically do not necessarily trigger any actions unless you specify them. You could look at binding listeners to html modifying on the div/table (grid) which would then invoke the height changes you're looking for if you'd rather keep that code out of the UJS files.

    Also, that $('#results') can be considerably shortened:

    $('#results').html("<%= j render 'songs/showcard', song: @song %>");
    
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决