Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

How can I call one JavaScript file for many HTML file?

I am trying to do website which has more than one page.
In the getYarismaciName function I am tryin to get cards (in the first HTML page) innerHTML and sending getJSON function. In this function I am trying to add some HTML code in .yarismaci-section (in the second page) using innerHTML but in this part I get "Uncaught TypeError: Cannot set property 'innerHTML' of null" error I guess js still searching yarismaci-section in the first HTML page but it is in the second page. How can I fix this error?

const cards = document.querySelectorAll(".card");

const getYarismaciName = function(){
cards.forEach((item) => {
    item.addEventListener("click",function(){
        let name=item.childNodes[3].innerHTML;
                
        getJSON(name);

    })
});
}
getYarismaciName();


const getJSON = function(name){
    const xhr = new XMLHttpRequest();
    xhr.open("GET","data.json",true);

    xhr.onload=function(){
        if(this.status===200){
            let yarismacilar = JSON.parse(this.responseText);
            let html="";
            yarismacilar.forEach(person => { 
                if(person.name===name){
                    html=`
                            <div class="yarismaci-img" id="yarismaci__img">
                            <img src="${person.image}" alt="${person.name}">
                            </div>
                            <div class="yarismaci-des">
                            <h3 id="yarismaci__kimdir">${person.name} Kimdir ?</h3>
                            <p id="yarismaci__budur">${person.info}</p>
                                </div>  
                        
                        `;
                }
            });
            document.querySelector(".yarismaci-section").innerHTML=html;
        }
    }
    
    xhr.send();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can check whether or not the element was found before trying to assign to it's innerHTML with an if statement.

Assign whatever is returned by the querySelector function to a variable then test to make sure that the variable isn't null or undefined before trying to use it.

let element = document.querySelector(".yarismaci-section");
if(typeof(element) != 'undefined' && element != null)
    element.innerHTML = "Found .yarismaci-section";
else
    document.querySelector(".different-div").innerHTML = "Could not find .yarismaci-section";
<div class="different-div"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...