【问题标题】:HTML elements disappear when navigating to the page, re-appear on page refreshHTML 元素在导航到页面时消失,在页面刷新时重新出现
【发布时间】:2019-11-10 18:39:36
【问题描述】:

在我的框架中使用 Ruby on Rails。 我已经编写了创建棋盘的代码。当我第一次导航到包含元素的包含 div 的页面时,我由 JavaScript 创建的 HTML 元素消失了。棋盘在一瞬间可见,然后在第一次导航到页面时消失,但刷新会使棋盘出现并保留。这是我的 JavaScript 文件:

    $(function() {
      var $boardContainer = document.querySelector('.board-container'); //grabs the div added to the index page -JB
      var $table = document.createElement("table"); 

      function buildBoard() {

        for (var i = 0; i < 8; i++) {   
            var $tr = document.createElement('tr');
            for (var n = 0; n < 8; n++) {
                var $td = document.createElement('td');
                $td.setAttribute('data-coord', i+','+n) //grabs the row iterator (i) and the cell iterator (n) and uses them for the coords! -JB
                if (i%2 == n%2) {           //every even square is white, odd is black -JB
                    $td.className = "white";
                } else {
                    $td.className = "black";
                }
                $tr.appendChild($td);
            }
            $table.appendChild($tr);
        }
        $boardContainer.appendChild($table);
      }
      buildBoard();
    });

这是元素附加到的元素:

<%= link_to 'Home', root_path, class: 'btn btn-primary'%>

<div class="board-container d-flex justify-content-center">



</div>

想弄清楚为什么棋盘在初始页面加载时不会保持呈现,但会在刷新时保持。

【问题讨论】:

    标签: javascript html ruby-on-rails


    【解决方案1】:

    听起来像 Turbolinks 导致了这种情况,而不是使用相当于 $(document).ready(function() { .. }) (L1) 的 $(function() { .. },您应该这样做:

    $(document).on('turbolinks:load', function() {
    
      // your code here
    
    })
    

    这是 Turbolinks 代码库供您参考:https://github.com/turbolinks/turbolinks

    L1:What does $(function() {} ); do?

    【讨论】:

    • 这正是问题所在,谢谢!我会检查一下 turbolink 还会导致哪些其他问题。
    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2021-07-03
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多