加载 jQuery 单击事件,即使在使用后退按钮 (Squarespace) 时也是如此

Load jQuery click events, even when using back button (Squarespace)

我正在尝试在常见问题页面上隐藏和显示段落。段落最初是隐藏的,我添加以下代码:

  $(document).ready(function() {
    $('h3').click(function() {$(this).next("p").toggleClass("unhidden-paragraph") } )
  })

unhidden-paragraph 设置样式以显示段落。因此,如果点击一个问题 (h3),则会显示该段落。

这非常有效,但是当我转到 Squarespace 上的另一个页面,然后使用后退按钮返回我的常见问题解答页面时。然后 ready 不再调用,点击 h3 问题不再有效。

要在用户从后退按钮进入页面时执行某些 jQuery 设置代码,您可以使用 $(window).on('pageshow') 而不是 $(document).ready():

$(window).on('pageshow', function(){
    $('h3').click(function() {$(this).next("p").toggleClass("unhidden-paragraph") } );
});

对于 "single-page" 设计(如 Squarespace),您可能需要直接将方法附加到 HTML 元素的 onclick 属性:

<h3 onclick='$(this).next("p").toggleClass("unhidden-paragraph");'>Title</h3>