首页 > 解决方案 > 使用数组时 parentElement.remove() 未定义

问题描述

问题: e1.parentElement.remove();未定义

调试: e1有一个值。e1.remove()删除一个按钮,但我需要删除一组按钮。

全局变量 & 运行函数

var x = 0;
AllResponses(null, null);

主要功能有机器人问题和预先制作的用户答案,用户可以点击

function AllResponses(e1, userPicked) {
    //user responsed 
    if (e1) {
        PrintUserResponse(e1, userPicked);
    }

    let BotQuestions = [
        ['Select the topic or write your question below.'],
        ['Before we start, our legal made us ask  <br/><br/> Do you agree to have your personal data processed by LiveChat, Inc.?', 'Click the button below to see our Privacy Policy.'],
        ['Great, let me just ask a couple of questions so I can find the right rep for you :)']
    ];

    let UserOptions = [
        ['Contact Sales', 'Free Trail', 'Getting Started', 'Features', 'Pricing', 'Contact suppot'],
        ['Agree', 'Disgree'],
        ['Dave']
    ];

   setTimeout(() => {
    // Bot question 
    if (x != BotQuestions.length) {
        var question = BotQuestions[x];
        for (var y = 0; y < question.length; y++) {
            let botHtml = '<p class="botText"><span>' + question[y] + '</span></p>';
            $("#chatbox").append(botHtml);
        }

        // user option 
        var option = UserOptions[x];
        for (var uy = 0; uy < option.length; uy++) {
            let userHtml = '<button type="button" class="btn btn-small btn-primary" onclick="AllResponses(this,\'' + option[uy] + '\')">' + option[uy] + '</button><br/>';
            $("#chatbox").append(userHtml);
        }
        x++;
    }
}, 1000)

    document.getElementById("chat-bar-bottom").scrollIntoView(true);
}

删除按钮,并显示点击了哪个按钮

function PrintUserResponse(e1, userPicked) {
    if (e1) {
        alert(e1.parentElement.remove());

        //remove pre options
        e1.parentElement.remove();

        //user pre-option
        let userHtml = '<p class="userText"><span>' + userPicked + '</span></p>';
        $("#chatbox").append(userHtml);

        document.getElementById("chat-bar-bottom").scrollIntoView(true);
    }
   
}

标签: javascriptarraysloopschatbot

解决方案


明白了,好像我必须将所有按钮分组到一个 div 中。比它工作正常。

        var option = UserOptions[x];
        let userHtml = '<div style="padding: 15px !important;">';
        for (var uy = 0; uy < option.length; uy++) {
            userHtml += '<button style="margin-bottom: 10px !important" type="button" class="btn btn-lg btn-default" onclick="AllResponses(this,\'' + option[uy] + '\')">' + option[uy] + '</button>&nbsp&nbsp&nbsp';
        }
        userHtml += "</div>";
        $("#chatbox").append(userHtml);

推荐阅读