gpt4 book ai didi

ruby-on-rails - 在 Rails 中使用 Turbolinks 5 时,我应该如何处理页面元素上的事件监听器?

转载 作者:行者123 更新时间:2023-12-03 22:39:48 26 4
gpt4 key购买 nike

根据 Turbolinks readme ,在使用 turbolinks:load 时,我们不应该直接在页面元素上设置事件监听器:

When possible, avoid using the turbolinks:load event to add event listeners directly to elements on the page body. Instead, consider using event delegation to register event listeners once on document or window.

既然如此,有时您需要在个别元素上设置监听器。推荐的方法是什么?使用不同的 Turbolinks 事件?还有别的吗?

最佳答案

如果事件是由用户触发的(点击、按键等),那么您可以简单地使用

$(document).on('click', '#id', function(e) {......

它工作得很好,因为它绑定(bind)到文档而不是可以更改或删除的类/id。尽可能使用它。

如果您需要页面加载某些内容,则必须使用 turbolinks:load ,如下所示。您需要这个,因为使用涡轮链接您不会进行真正的整页重新加载,但您必须以某种方式告诉浏览器您已经在不同的页面上。

$(document).on('turbolinks:load', function() {
$('.class').geocomplete();
});

关于ruby-on-rails - 在 Rails 中使用 Turbolinks 5 时,我应该如何处理页面元素上的事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39472936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com