简体   繁体   中英

Using JavaScript to clear array values on buttons onclick?

Learning JS and needed some help. Thanks to stack overflow, I now have a function that displays list of subjects onload. I'd like the button values to clear when clicked and replaced with array of second function. This is creating a new set of buttons, I can see where the problem is but not sure how to correct it. I've tried a few ways but no luck, here is the basic code. It is assigned to 'subjects' div in HTML doc.

let subjectArray = ['Maths', 'English', 'Science', 'IT'];

function printSubjects() {
    for (let i = 0; i < subjectArray.length; i++) {
        let sub = document.createElement('button');
        let txt = document.createTextNode(subjectArray[i]);
        sub.append(txt);
        subjects.appendChild(sub);
        sub.className = "btn btn-outline-primary mb-2";
    }
}
let testArray = ['Test 1', 'Test 2', 'Test 3', 'Go Back'];
function printTest() {
    for (let i = 0; i < testArray.length; i++) {
        let test = document.createElement('buttons');
        let txt = document.createTextNode(testArray[i]);
        test.append(txt);
        subjects.append(test);
        test.className = "btn btn-outline-secondary mb-2";
    }
}
window.onload = printSubjects();

document.body.addEventListener("click", printTest, {
    once: true
})

By clearing the innerHTML of the parent Div will work.

document.getElementById("subject").innerHTML = "";

Working Demo:

 let subjectArray = ['Maths', 'English', 'Science', 'IT']; let testArray = ['Test 1', 'Test 2', 'Test 3', 'Go Back']; let subjects = document.getElementById("subject"); function printSubjects() { for (let i = 0; i < subjectArray.length; i++) { let sub = document.createElement('button'); let txt = document.createTextNode(subjectArray[i]); sub.append(txt); subjects.appendChild(sub); sub.className = "btn btn-outline-primary mb-2"; } } function printTest() { document.getElementById("subject").innerHTML = ""; for (let i = 0; i < testArray.length; i++) { let test = document.createElement('button'); let txt = document.createTextNode(testArray[i]); test.append(txt); subjects.append(test); test.className = "btn btn-outline-secondary mb-2"; } } window.onload = printSubjects(); document.body.addEventListener("click", printTest, { once: true })
 <div id="subject"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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