正如标题所示,我的主要目标是在 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
的 CSS。
我的所需的 CSS 看起来像这样,它检查 li 元素是否属于集合,如果属于,则为它们提供边框颜色。
ul#list > li[data-collections~='8'][data-collections~='2']
{
border-color: #ff2900;
}
我将其添加到我的 Controller 中以生成[]-条件
:
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
到我的 Controller ,有文件views/collections/toggle.css.erb
ul#list<%= raw active_collections %> > li<%= raw active_collections %> {
border-color: #ff2900;
}
它不起作用,另一种方法是从我的 Controller 渲染 css 文件,然后将其传递到 View ,如Manuel Meurer所述。
我是否搞乱了文件名?喜欢使用 css
而不是 scss
吗?您有什么想法我应该如何进行吗?
感谢您的帮助!
为什么是动态 CSS? - 推理
我知道这通常应该通过 JavaScript 添加类来实现。我为什么需要动态 CSS 的原因是,当用户决定更改所选集合时,他会非常集中地执行此操作。比如 3 秒内 4 个调用,然后暂停 5 分钟,然后 4 秒内 5 个调用。每次调用后,JavaScript 都会花费太长时间来循环 50 多个 li
。
更新
事实证明,JavaScript 处理我的“长”列表的速度非常快...谢谢你们指出我的想法中的错误!
最佳答案
在我看来,你遇到的问题与 CSS 无关;而是与 CSS 有关。这与您的系统如何工作有关
CSS 是静态加载的(来自 http 请求),这意味着当页面呈现时,如果您更改服务器上的 CSS 文件,它不会更新
JS 是客户端,旨在与渲染的 HTML 元素交互(通过 DOM)。这意味着 JS 本质上是动态的,这就是为什么我们可以将它与 Ajax 等技术一起使用来更改页面的某些部分
这就是我认为你的问题所在......
您的 JS 调用不会重新加载页面,这意味着 CSS 保持静态。目前无法重新加载 CSS 并在不刷新(发送 HTTP 请求)的情况下渲染它们。这意味着您使用 JS 进行的任何更新都必须包含预加载的 CSS
根据对您的OP的评论,您应该真正考虑更新列表元素的类。如果你使用这样的东西,它应该立即起作用:
$('li').addClass('new');
希望这有帮助吗?
关于ruby-on-rails - 使用 ajax、rails 渲染动态 scss 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377051/