在我的框架中使用 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>
想要弄清楚为什么棋盘在初始页面加载时不会保持渲染状态,但会在刷新时保持渲染状态。
最佳答案
听起来像是 Turbolinks 导致了这种情况,而不是执行 $(function() { .. }
,这相当于 $(document).ready(function() { .. })
(L1),你应该这样做:
$(document).on('turbolinks:load', function() {
// your code here
})
以下是 Turbolinks 存储库供您引用:https://github.com/turbolinks/turbolinks
关于javascript - HTML 元素在导航到页面时消失,在页面刷新时重新出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791799/