导航到页面时,HTML元素消失,并在页面刷新时重新出现

在我的框架中使用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>

想弄清楚为什么棋盘在初始页面加载时不会保持渲染,而是在刷新时保持不变。

zhang0013hao 回答:导航到页面时,HTML元素消失,并在页面刷新时重新出现

诸如Turbolinks之类的声音是造成这种情况的原因,而不是像$(function() { .. }(L1)那样做$(document).ready(function() { .. }),应该这样做:

$(document).on('turbolinks:load',function() {

  // your code here

})

以下是Turbolinks存储库供您参考:https://github.com/turbolinks/turbolinks

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

本文链接:https://www.f2er.com/3128011.html

大家都在问