Javascript 绑定到 link_to 是否在页面加载时执行?
Javascript tied to link_to is being executed on page load?
我有一个加载大量记录的索引页。每条记录都有一个 "favorite" 图标。单击 "favorite" 向服务器发送 POST
并重新加载页面。
我正在尝试使用 jQuery (ujs??) 作为 POST
。
控制器操作现在看起来像这样:
def favorite
@record = Record.find(params[:id])
@record.toggle_flag("favorite")
end
最喜欢的图标正在 index
视图中呈现,是 link_to
:
<%= link_to(
icon,
path,
method: :post,
remote: true
) %>
app/views/records/favorite.js.erb
文件如下所示:
console.log("I am executing");
$("[data-id='icon']").update("<%= j render 'icon', { icon: @record.favorite_icon, path: favorite_record_path } %>");
当我尝试加载 index
时,我收到一条错误消息,指出 @record 为 nil。但是为什么js在加载index
的时候就被执行了呢?此外,控制台日志在加载 index
时会立即触发。我希望 JS 在单击收藏图标时执行。
您的代码在我看来很完美,应该可以正常工作而不会出现此类错误。似乎其他一些 js 代码在页面加载时触发 link 单击事件。所以也尝试搜索一下。
favorite.js.erb
将仅在 js 请求上执行,而不是在 html 请求上执行,页面加载是 html 请求。
所以尝试找到触发点击事件的js代码。
我有一个加载大量记录的索引页。每条记录都有一个 "favorite" 图标。单击 "favorite" 向服务器发送 POST
并重新加载页面。
我正在尝试使用 jQuery (ujs??) 作为 POST
。
控制器操作现在看起来像这样:
def favorite
@record = Record.find(params[:id])
@record.toggle_flag("favorite")
end
最喜欢的图标正在 index
视图中呈现,是 link_to
:
<%= link_to(
icon,
path,
method: :post,
remote: true
) %>
app/views/records/favorite.js.erb
文件如下所示:
console.log("I am executing");
$("[data-id='icon']").update("<%= j render 'icon', { icon: @record.favorite_icon, path: favorite_record_path } %>");
当我尝试加载 index
时,我收到一条错误消息,指出 @record 为 nil。但是为什么js在加载index
的时候就被执行了呢?此外,控制台日志在加载 index
时会立即触发。我希望 JS 在单击收藏图标时执行。
您的代码在我看来很完美,应该可以正常工作而不会出现此类错误。似乎其他一些 js 代码在页面加载时触发 link 单击事件。所以也尝试搜索一下。
favorite.js.erb
将仅在 js 请求上执行,而不是在 html 请求上执行,页面加载是 html 请求。
所以尝试找到触发点击事件的js代码。