我正在我的Rails应用程序中实现Switchery按钮,并且Turbolinks处于打开状态。当我导航到另一个页面,然后单击“后退”按钮时,该按钮正在被复制。
以下是我的Javascript代码:
$(document).on('turbolinks:load', function() {
var elem = document.querySelector('.js-switch');
var switchery = new Switchery(elem, {className:"switchery switchery-small"});
});Html视图:
<b>Assign as administrator?<span> <%= f.check_box :admin, class:"js-switch" %></span></b>截图:View
那么我该如何处理这个问题呢?
发布于 2020-08-17 17:42:20
Multiple calls防止在同一元素上调用switchery两次,但对turbolink没有帮助。当页面从缓存中获取时,当它们被添加到DOM中时,它的点击/更改事件需要重新初始化。我发现的唯一方法是删除现有的元素(看起来它们只是视觉元素),然后重新初始化它们。turbolinks:load函数如下所示:
$(document).on('turbolinks:load', function(e) {
// Delete existing switches if there are any...
$(".switchery").remove();
// As we removed all the switchery elements, we need fetch all of them again.
var els = document.querySelectorAll(".js-switch");
els.forEach(function(el) {
new Switchery(el);
})
});发布于 2020-03-11 22:06:19
您可以通过查找data-switchery="true“来过滤掉已经被调用的现有元素。
var elem = document.querySelector('.js-switch:not([data-switchery])');https://stackoverflow.com/questions/60634478
复制相似问题