[英]Rails: after rendering partial with Ajax, manipulating that partial with JS
[英]Rails 6: execute a JS function after rendering partial
Rails & Javascript 初學者在這里,
在一個培訓項目中,我使用 JQuery 使flash
消息在幾秒鍾后消失。訪問者會發送 AJAX 請求將產品添加到他的購物車,然后 flash 部分“已添加到購物車”出現並在幾秒鍾后自動淡出。
# application.html.erb
<div id='flash' class='flex-column'>
<%= render partial: 'shared/flash' %>
</div>
# shared/_flash.html.erb
<% flash.each do |key, value| %>
<%= display_flash(key, value) %>
<%= javascript_pack_tag 'custom/flash' %>
# this works, but injects the script each times the partial is rendered
<% end %>
# helpers/application_helper.rb
def display_flash(key, value)
def display_flash(key, value)
div_class = [flash_class(key), 'text-center fade show alert-dismissible'].join(' ')
content_tag(:div, class: div_class) do
content_tag(:p, value) +
button_tag(class: 'ml-auto close', 'data-dismiss': 'alert', type: 'button') do
content_tag(:span, '×'.html_safe, 'aria-hidden': 'true') +
content_tag(:span, 'Close', class: 'sr-only')
end
end
end
end
// app/javascript/packs/custom/flash.js
function closeFlash(){
let lastAlert = $('#flash .alert:last')
function fadeFlash() {
lastAlert.animate( {opacity: 0}, 2000, function() {
$(this).hide('slow', function() {
$(this).remove()
});
});
};
setTimeout(fadeFlash, 2000)
};
closeFlash();
這可以修復,但是是否有合適的方法在渲染(AJAX)部分后執行一個特定的 javascript function? 在我的例子中,每次呈現部分時執行位於packs/custom/flash.js
中的closeFlash()
。
感謝您的幫助和您的時間
來自 Amit Patel 的回答和這篇文章
// app/javascript/packs/custom/flash.js
window.closeFlash = function() {
let lastAlert = $('#flash .alert:last')
function fadeFlash() {
lastAlert.animate( {opacity: 0}, 2000, function() {
$(this).hide('slow', function() {
$(this).remove()
});
});
};
setTimeout(fadeFlash, 2000)
};
// app/javascript/packs/custom/flash.js window.closeFlash = function() { let lastAlert = $('#flash.alert:last') function fadeFlash() { lastAlert.animate( {opacity: 0}, 2000, function() { $(this).hide('slow', function() { $(this).remove() }); }); }; setTimeout(fadeFlash, 2000) };
它不會注入整個 function 但(我相信)最小的 javascript 代碼來調用它。
將<%= javascript_pack_tag 'custom/flash' %>
移動到您的布局或 application.js` 中,以便在整個應用程序中可用。
修改您的模板,例如
<div id='flash' class='flex-column'>
<%= render partial: 'shared/flash' %>
<script>
$(function(){
closeFlash();
});
</script>
</div>
更新的方法是設置刺激 controller。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.