简体   繁体   English

如何删除附加元素?

[英]How can i remove an appended element?

I'm doing an exercise from javascriptissexy.com, the exercise is to build a quizzer. 我正在javascriptissexy.com进行练习,练习是建立测验者。 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. 我试图显示一个基于变量页面值的问题,问题存储在数组对象中,当单击下一步按钮时,页面变量将增加1,并显示下一个问题及其选择。

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() . 好吧,不是每次都使用.append() ,而是可以在$("legend").children()使用.replaceWith() $("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. 在每种情况下,它将替换$("legend")内容。

Edit: 编辑:

Or best approach would be to use .html() method like this: 或最好的方法是使用.html()方法,如下所示:

$("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? 我看到您通过使用相同的语句在每种情况下都做相同的事情, switch块的目的是什么?

Not sure if you use jQuery but; 不确定是否使用jQuery,但是; using jQuery empty() function you can easily remove previously added question like: 使用jQuery empty()函数,您可以轻松删除以前添加的问题,例如:

$('legend').empty();

You can find more information here: jQuery API empty() function 您可以在此处找到更多信息: jQuery API empty()函数

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

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