簡體   English   中英

在另一個 js 文件中進行 dom 操作后,如何運行 javascript 文件?

[英]How can I run javascript file after dom manipulation made in another js file?

當我運行我的 Rails 應用程序並在控制台中輸入 likeButton 時,它給我 Uncaught ReferenceError: likeButton is not defined at:1:1 (anonymous) @ VM1591:1 我嘗試將 html 中的腳本移動到頭部和身體。 我目前正在嘗試使用 DOMContentLoaded 但似乎我遺漏了一些東西。 我的總體目標是在按下按鈕后更改按鈕的顏色,並在頁面刷新后保持顏色。 我正在為此過程使用 sessionStorage。 我只想確保在加載 html 之后聲明了 likeButton 變量。 如果可能的話,只能在 javascript 中完成。

//first js file
const BASE_URL = "http://localhost:3000"
const GPUS_URL = `${BASE_URL}/gpus`
const USERS_URL = `${BASE_URL}/users`

const gpuCollection = document.querySelector('#gpu-collection')

let wish = sessionStorage.getItem('wish');

class Gpu {
    constructor(gpuAttributes) {
        this.title = gpuAttributes.title;
        this.price = gpuAttributes.price;
        this.features = gpuAttributes.features;
        this.link = gpuAttributes.link;
        this.image = gpuAttributes.image;
        this.id = gpuAttributes.id;

    }

    render() {
        let div = document.createElement('div');
        div.classList.add('card');

        let h = document.createElement('h2');
        let t = document.createTextNode(`${this.title} ($${this.price})`);
        h.appendChild(t);
        div.appendChild(h);

        let h1 = document.createElement('h1');
        h1.classList.add('gpu-cat');
        h1.innerHTML = `${this.features}`;
        div.appendChild(h1);

        let button = document.createElement('button');
        button.classList.add('list_btn');
        button.innerHTML = '♡';
        div.appendChild(button);
        
        let a = document.createElement('a');
        let img = document.createElement('img');
        a.href = `${this.link}`;
        a.target = '_blank';
        img.src = `${this.image}`;
        img.classList.add('gpu-image');
        a.appendChild(img);
        div.appendChild(a);
        gpuCollection.appendChild(div);
    }

}
//second js file
document.addEventListener("DOMContentLoaded", function (){

let likeButton;

SignUp();
logInUser();
logOutUser();

function putGpusOnDom(gpuArray){
     gpuArray.forEach(gpu => {
       let newGpu = new Gpu(gpu)
        newGpu.render()
      }); 
         likeButton = document.querySelector("button"); 

                }  

function fetchGpus(){
            fetch(GPUS_URL)
            .then(res => res.json())
            .then(gpus => putGpusOnDom(gpus))
    }

const enableWish = () => {
            
            console.log(likeButton)
            sessionStorage.setItem('wish', 'red')
         }

 gpuCollection.addEventListener('click', function (){
            wish = sessionStorage.getItem('wish');
   
            if(wish !== 'red'){
                enableWish();
            }else{
                disableWish();
            }
        });

})
//html file
...
 <body>
<div id = "gpu-collection"></div>
    
<script type="text/javascript" src="src/Gpu.js"></script>
    <script type="text/javascript" src="src/index.js" ></script>
  </body>
</html>

正如我在評論中提到的,如果它是動態添加的,則點贊按鈕在DOMContentLoaded上不可用。 您需要等到按鈕被放置在 DOM 中

使用類似下面的內容,我在這里進行一些猜測,因為您的代碼中存在一些差距

document.addEventListener("DOMContentLoaded", function (){

//document.querySelector("button"); not yet available
//NOTE: The likeButton variable will ONLY be in scope INSIDE the event listener function
//      You will not be able to access directly in the console.
let likeButton;

SignUp();
logInUser();
logOutUser();

function putGpusOnDom(gpuArray){
     gpuArray.forEach(gpu => {
       let newGpu = new Gpu(gpu)
        newGpu.render()
      });
      //Now you have rendered the button it is available
      //CAUTION: querySelector("button") will grab the first button on the page 
      //         and ONLY the first button
      likeButton = document.querySelector("button");    
      //Log like button to console while it is still in scope.
      console.log(likeButton);
}  

function fetchGpus(){
            fetch(GPUS_URL)
            .then(res => res.json())
            .then(gpus => putGpusOnDom(gpus))
    }

const enableWish = () => {
            
            console.log(likeButton)
            sessionStorage.setItem('wish', 'red')
         }

})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM