【问题标题】:How to add each item of an array into separate HTML elements using jQuery?如何使用 jQuery 将数组的每个项目添加到单独的 HTML 元素中?
【发布时间】:2015-02-27 23:24:47
【问题描述】:

我看了看,没有找到另一个问这个关于 jQuery 的问题。如果有请指点一下。

这是我的功能:

function PopAnswers(aelement, adata) {
    var answerCount = 1;
    for(var i = 0; i < adata.length; i++) {
        $("aelement" + answerCount).text(adata[i]);
            answerCount++;
    };
}

我的问题对象:

var question1 = new QuestionBlock(
    "What is the correct jQuery code to set the background color of all p elements to red?",
    [
    '$("p").manipulate("background-color","red");',
    '$("p").style("background-color","red");',
    '$("p").css("background-color","red");',
    '$("p").layout("background-color","red");'
    ],
    2);

电话:

$("#progressbar h1").click(function() {     
            PopAnswers("#answer", question1.answers);       
    });

这是 HTML:

<div id="answerbox">
                <div class="answer" id="answer1">
                    <p></p>
                </div>
                <div class="answer" id="answer2">
                    <p></p>
                </div>
                <div class="answer" id="answer3">
                    <p></p>
                </div>
                <div class="answer" id="answer4">
                    <p></p>
                </div>
            </div>

我正在尝试用数组元素填充每个#answer 元素。 我可以得到一些帮助,希望有一个很好的解释,这样我就可以理解并且不必再次查找这个问题? 谢谢

【问题讨论】:

  • 您需要在 PopAnswers 的第 4 行去掉双引号:` $(aelement + answerCount).text(adata[i]);` 因为 aelement 是这里的变量名。

标签: jquery html arrays


【解决方案1】:

您在 jQuery 选择器中引用了一个不存在的元素

改变这个:

$("aelement" + answerCount).text(adata[i]); // will try to fetch aelement1

进入这个:

$(aelement + answerCount).text(adata[i]); // will try to fetch #answer1

【讨论】:

  • 现在我觉得自己很愚蠢。我知道我很接近了!在 2 分钟内打勾。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多