简体   繁体   English

Rails 6 javascript 文件没有正确抓取 html 元素

[英]Rails 6 javascript file isn't grabbing html element properly

New to Javascript. Javascript 新手。 I'm following a javascript tutorial to create a simple tictactoe game and I'm trying to adapt the code to work on Rails.我正在按照 javascript 教程创建一个简单的 tictactoe 游戏,并且我正在尝试调整代码以在 Rails 上工作。

I have a JavaScript file with a function that is supposed to run once cell element is clicked.我有一个 JavaScript 文件,其中的函数应该在单击cell元素后运行。

When I load the page script js file loaded is displayed from console.log("script js file loaded") in the console so i know the javascript file is being loaded.当我加载页面时,加载的script js file loadedconsole.log("script js file loaded") ,所以我知道正在加载 javascript 文件。

I suspect the rails js syntax is a little different from vanilla js?我怀疑 rails js 语法与 vanilla js 有点不同?

app/views/tictactoe/index.html.erb : app/views/tictactoe/index.html.erb

<%= javascript_pack_tag 'script' %>

<div class="board" id="board">
    <!--- add data cell so can access in javascript   -->
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>
    <div class="cell" data-cell></div>

</div>

app/javascript/packs/script.js

const cellElements = document.querySelectorAll('[data-cell]')

// loop through each cell, add event listener, every time cell is clicked, add this listener (handleClick),
// once:true --> once clicked once, wont fire again
cellElements.forEach(cell => {
    cell.addEventListener('click', handleClick, {once: true})
})

function handleClick(e){
    console.log('clicked')
}

console.log("script js file loaded")

Any help is appreciated thank you.感谢您提供任何帮助。

@numbers1311407 是正确的,在您的application.html.erb您可以使用defer:true使您的 JS 在加载 DOM 后运行。

<%= javascript_pack_tag 'application', defer: true %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM