简体   繁体   中英

How can i remove an appended element?

I'm doing an exercise from javascriptissexy.com, the exercise is to build a quizzer. i'm trying to show a question based on the variable page value, question are stored in array object, when a the next button is clicked the page variable is incremented by 1 and the next question is shown with its choices.

What I want to do is after the next button click, remove the previous appended question and its choices.. how can i do this?

function createQuiz(crPage) {
    textNode = Allquestions[indexController].question;
    switch (crPage) {
        case 0:
            $("legend").append(textNode);
            appendChoices()
            break;
        case 1:
            $("legend").append(textNode);
            appendChoices()
            break;
        case 2:
            $("legend").append(textNode);
            appendChoices()
            break;
        case 3:
            $("legend").append(textNode);
            appendChoices()
            break;
        case 4:
            $("legend").append(textNode);
            appendChoices()
            break;
        case 5:
            $("legend").append(textNode);
            appendChoices()
            break;
        case 6:
            $("legend").append(textNode);
            appendChoices()
            break;

        default:
            // code

    }
}


function appendChoices() {
    for (var i = 0; i < Allquestions[indexController].choices.length; i++) {
            console.log(Allquestions[indexController].choices[i]);
    }
}

Well instead of using .append() each time, you can use .replaceWith() over $("legend").children() .

For example the code in each case will look like this:

$("legend").children().replaceWith(textNode);
appendChoices()
break;

It will replace the $("legend") content in each case.

Edit:

Or best approach would be to use .html() method like this:

$("legend").html(textNode);
appendChoices()
break;

Note:

I see that you are doing the same thing in each case, by using the same statements, what's the purpose of the switch block?

Not sure if you use jQuery but; using jQuery empty() function you can easily remove previously added question like:

$('legend').empty();

You can find more information here: jQuery API empty() function

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