在我的框架中使用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>
想弄清楚为什么棋盘在初始页面加载时不会保持渲染,而是在刷新时保持不变。