【问题标题】:Trying to append an array of html elements to a div element on a page with jquery but it's not showing [duplicate]尝试使用 jquery 将 html 元素数组附加到页面上的 div 元素,但未显示 [重复]
【发布时间】:2023-04-03 15:27:01
【问题描述】:

我正在尝试将 html 元素数组添加到页面上的 div 元素,但它没有显示。当我在 div 元素上执行 console.log 时,它会打印数组,确认数组已添加到 div 元素但它没有出现在页面上。下面是我正在尝试做的代码:

html:

<form action="question" method="post">
    <div class="combobox">
        <label for="switchQuestion">Switch Question:</label>
        <select id="switchQuestion"></select>
    </div>
    <div id="go-btn">
        <input id="go" type="button" value="Go" />
    </div>
</form>

<div class="exam-container">
    <div id="exam-question"></div>
</div>

jquery:

const $examQuestions = $('#exam-question'),
output = [];

loadQuestions($examId, function(question){
    for(let i in question) {
        $switchQuestion.append($('<option />').val(question[i].id).text(Number(i)+1));
        loadChoices(question[i].id, question[i].multiAnswer, function(choices) {
            output.push(
                    `<div class='question'> ${(Number(i)+1)}. ${question[i].problemDescription} </div>
                     <div class='choices'> ${choices.join('')} </div>`
            );
        });
    }
});

output.join('');
$examQuestions.innerHTML = output;

function loadChoices(id, isMulti, callback) {
    let choices = [];
    $.ajax({
        url: location.protocol + '//' + location.host + '/online-test-exam-maker' +'/choices/' + id,
        dataType: 'json',
        type: 'GET',
        success: function (data, status) {
            let elemType = isMulti ? 'checkbox' : 'radio';
            $.each(data, function (i, v) {
                choices.push(
                    `<label>
                      <input type='${elemType}' name='${v.questionId}' value='${v.id}' id='${v.id}' />
                      ${v.choiceText}
                     </label>`
                );
            });
            if(typeof callback === 'function') {
                callback(choices);
            }
        },
        error: function(){
        }
    });
}

【问题讨论】:

  • $examQuestions.html(输出)
  • @Pavlo 抱歉,这是一个错误,我已更正。
  • 还是错了,jQuery中不存在innerHTML,改用.html()
  • 我也尝试过 .html() 和 .append() 但仍然没有显示在页面上。有了这些,当我执行 console.log($examQuestions) 时,数组不会添加到 div 元素中
  • 对不起,你能告诉我 $switchQuestion 和 loadChoices 吗?

标签: javascript jquery html arrays


【解决方案1】:

如果您想替换 div 中的所有内容,请执行以下操作:

$examQuestions.html(output)

否则你也可以使用 jQuery 的 append 方法,例如:

$examQuestions.append(output)

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2010-11-13
    • 1970-01-01
    相关资源
    最近更新 更多