【问题标题】:can't create html content in a loop无法在循环中创建 html 内容
【发布时间】:2014-04-11 20:25:56
【问题描述】:

我正在尝试使用从 xml 读取内容的 javascript 在循环中的部分 html 元素下创建新的文章 html 元素,但我得到的只是循环的最后一篇文章。

//variable holds a specific section element
var section = document.getElementById('articles');

//monument variable holds 2 monument elements from xml
for (var i = 0; i < monument.length; i++) {

    //create articles elements
    var article = document.createElement('article');

    //create the title of the article
    article.innerHTML += "<h3>";

    //the title variable holds 2 title elements from xml
    article.innerHTML += title[i].childNodes[0].nodeValue;
    article.innerHTML += "</h3>"

    //append article to section
    section.appendChild(article);

} //end of for

你能找出原因吗?

【问题讨论】:

  • 你能把你所有的代码都放在jsfiddle里吗?
  • 我会尝试,否则我会在这里插入所有代码
  • 我收到消息“document.write 在 JSFiddle 环境中是不允许的,可能会破坏你的小提琴。”

标签: javascript xml html dom


【解决方案1】:

我将两个元素数组分配给您的变量进行测试。

var monument = ['1', '2'],
    title = ['1', '2'];

http://jsfiddle.net/YP7fj/

效果很好。

所以,问题出在您的 monumenttitle 变量中。

您显示的代码没有任何问题。

【讨论】:

  • 是的,这也是我想出来的。我试图找出标题和纪念碑变量的问题
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 2016-10-17
相关资源
最近更新 更多