【发布时间】:2013-10-23 00:16:08
【问题描述】:
正如标题所示,我的主要目标是在 ajax 调用之后呈现动态 scss(.erb) 文件。
assets/javascripts/header.js
// onChange of a checkbox, a database boolean field should be toggled via AJAX
$( document ).ready(function() {
$('input[class=collection_cb]').change(function() {
// get the id of the item
var collection_id = $(this).parent().attr("data-collection-id");
// show a loading animation
$("#coll-loading").removeClass("vhidden");
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// removal of loading animation, a bit delayed, as it would be too fast otherwise
setTimeout(function() {
$("#coll_loading").addClass("vhidden");
}, 300);
},
});
});
});
controller/collections_controller.rb
def toggle
# safety measure to check if the user changes his collection
if current_user.id == Collection.find(params[:id]).user_id
collection = Collection.find(params[:id])
# toggle the collection
collection.toggle! :auto_add_item
else
# redirect the user to error page, alert page
end
render :nothing => true
end
当我单独切换数据库对象时,一切都非常顺利。
现在我想添加一些额外的香料,并根据用户当前选择的集合更改我的 50+ li's 的 CSS。
我的 desired CSS 看起来像这样,它检查 li 元素是否属于集合,如果属于,则给它们一个边框颜色。
ul#list > li[data-collections~='8'][data-collections~='2']
{
border-color: #ff2900;
}
我将此添加到我的控制器以生成 []-conditions:
def toggle
# .
# .
# toggle function
# return the currently selected collection ids in the [data-collections]-format
@active_collections = ""
c_ids = current_user.collections.where(:auto_add_item => true).pluck('collections.id')
if c_ids.size != 0
c_ids.each { |id| @active_collections += "[data-collections~='#{id}']" }
end
# this is what gets retrieved
# @active_collections => [data-collections~='8'][data-collections~='2']
end
现在我需要一种方法将这些括号放入动态生成的 scss 文件中。
我尝试添加:
respond_to do |format|
format.css
end
到我的控制器,拥有文件 views/collections/toggle.css.erb
ul#list<%= raw active_collections %> > li<%= raw active_collections %> {
border-color: #ff2900;
}
它不起作用,另一种方法是从我的控制器渲染 css 文件,然后将其传递给 Manuel Meurer 所描述的视图
我弄乱了文件名吗?喜欢使用css 而不是scss?你有什么想法我应该如何进行吗?
感谢您的帮助!
为什么选择动态 CSS? - 推理
我知道这通常应该通过 JavaScript 添加类来实现。我为什么需要动态 css 的原因是,当用户决定更改选定的集合时,他会非常专注。比如 3 秒内打 4 个电话,然后暂停 5 分钟,然后在 4 秒内打 5 个电话。每次调用后,JavaScript 将花费太长时间来循环遍历 50+ li's。
更新
事实证明,JavaScript 在处理我的“长”列表方面非常快...感谢大家指出我的想法中的错误!
【问题讨论】:
-
我不明白为什么需要动态 CSS。为什么不使用静态 CSS 并通过 jQuery 切换 div 的类,这很简单。
-
如果您想加载动态 CSS 文件,我认为您必须使用 javascript 将
<link rel>元素附加到您的 HTML 页面。但正如@BillyChan 所说,没有必要走那么远……如果你想根据特定条件应用样式,那么使用 javascript。如果该样式将应用于多个元素,则将该样式插入页面的head元素。 -
感谢您的输入,我通常会站在您这边,为什么我想使用 CSS 而不是 JavaScript 是因为我的
ul可以有 50+li's。在每一个小开关之后都通过它们会使我的应用程序超级慢...... -
在 JS 中循环 50 个元素不会那么慢,至少不会比另一个 HTTP 请求慢。
-
嗯,谢谢,我再试试 JS 的解决方案,可能是我上次搞砸了,我明天给大家看看结果
标签: ruby-on-rails ajax ruby-on-rails-3 dynamic sass