嘿,我在.js.erb
文件中遇到了一些奇怪和意外的行为。提供了相关代码和片段以供快速阅读以帮助理解问题。
orders_controller
仅高级搜索功能的部分片段
def advanced_search
@filters = params[:filters] || {}
@is_ajax_search = true
if @filters.present?
response = RestClient.post "my_url/orders/" +@filters.to_json
@orders = JSON.parse response.body
logger.debug [params[:offset], params[:limit], @orders["total"]]
limit = params[:limit] = 50
@orders["order_items"] = @orders["order_items"].paginate(
:page => params[:page],
:per_page => limit,
:total_entries=>@orders["total"]
)
@title = "Advanced Search"
render
end
end
orders/advanced_search.html.erb
<%# debug @orders %>
<% content_for :head do %>
<%= javascript_include_tag 'advanced_search_oms', %>
<% end %>
<%= render "advanced_search_orders_form" %>
<div id="advanced_search_orders_table" class="fk-table ajax">
<%= render "advanced_search_orders_table" %>
</div>
orders/_advanced_search_orders_table
<%= will_paginate @orders["order_items"] %>
javascripts/advanced_search_oms
$(function () {
$('.pagination a').click(function () {
alert("The url will no longer change")
return false;
});
});
但我实际上想在 中定义这个函数advanced_search.js.erb
,因为我需要使用实例变量。
orders/advanced_search.js.erb
alert("Hello") //Works when a page link is clicked using the will paginate. But is not displayed when the page is loaded. I wonder why?
$(function () {
alert("Dom is loaded") //Woks like previous alert. Only on page click.
$('.pagination a').click(function () {
alert("The url shouldn't change") //But it does. NO ALERT BOX even pops up. It's as if the function doesn't exist.
<%= logger.info "Entered js" %> //But this worked
return false;
});
});
你能帮我理解为什么会发生这种情况,我应该如何重新定义这个函数?