我的语法可能有点偏离,但我会这样做:
HTML
<div data-id="<%= @article.id %>" class="article"><%= @article.title %></div>
JS
这可能有助于解释您的 js 将如何工作: http: //guides.rubyonrails.org/asset_pipeline.html。我通常做的是为特定视图创建一个包含我的所有绑定(和其他方法)的对象。然后在视图的底部某处,我将在文档就绪块中创建对象的实例并绑定 DOM。您的所有 js 都将通过清单文件 (application.js) 添加到布局中的任何位置。
应用程序/资产/javascripts/users.js
// Wraps your binding in a document ready function
// Runs as soon as the DOM is loaded
$(function() {
$('.article').on('click', function() {
var id = $(this).attr('data-id');
$.get('articles/' + id, function(data) {
// Handle the result
$('.article-window').html(data);
});
});
});
应用程序/资产/javascripts/application.js
// This directive will include all your js files in the javascripts folder
//= jquery
//= require_tree .
app/views/layouts/application.html.erb (或任何你的布局)
// This adds all your js to the page
<%= javascript_include_tag "application" %>
导轨控制器
class ArticlesController < ApplicationController
respond_to :html, :json
def show
@article = Article.find(params[:id]
respond_with do |format|
format.json { render :json => @article }
end
end
end