javascript - Rails、turbolinks 和 javascript。如何避免出现重复的 Switchery 按钮?
问题描述
我正在我的 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>
截图: 查看
那么我该如何处理这个问题呢?
解决方案
多次调用可防止在同一元素上调用两次切换器,但这对 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);
})
});
推荐阅读
- html - 如何在另一个框架中打开参考
- javascript - 在 NextJS 路由中的 slug 前面添加符号(例如 @)
- javascript - 在反应中循环两个数组
- c# - C# 和 Xpath - 在单个 Xpath 查询中使用节点集和字符串类型返回结果
- php - 如何让 Auth::user() 返回在测试中使用工厂创建的用户?
- javascript - Nodejs 嵌套子进程未运行 | 子进程 | 节点
- java - 从 JWK 生成公钥
- javascript - 如何更改 webRTC 流的视频源 ID?
- sql - 奇怪的用逗号连接
- android - 使用 React Native 应用程序在哪里存储用于身份验证的用户密码