简体   繁体   English

使用javascript和jquery为值字符串编写HTML?

[英]Writing HTML for a string of values using javascript and jquery?

I want to have my page's html to appear as: 我希望页面的html显示为:

<div class='container'>
  <div class='domain-list0'>Hello</div>
  <div class='domain-list1'>World</div>
</div>

Here is my html and js: Pen from Codepen.io 这是我的html和js: Codepen.io的笔

Instead of creating the first "domain-list" and then creating another one for the next, it is just overwriting the previous "domain-list". 而不是创建第一个“域列表”,然后为下一个创建另一个域列表,它只是覆盖了先前的“域列表”。 This is why it shows the last string value. 这就是为什么它显示最后一个字符串值的原因。 Anyone know how to fix this? 有人知道怎么修这个东西吗?

Thanks! 谢谢!

You are using .html() which removes the existing content, and replaces it with the new content. 您正在使用.html()删除现有内容,并将其替换为新内容。 You need to use append so that the new content is added after the last child. 您需要使用append,以便在最后一个子项之后添加新内容。

var myStringArray = ["Hello", "World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    var $el = $("<div  />", {
        'class': 'domain-list' + i,
        html: "<p>" + myStringArray[i] + "</p>"
    }).appendTo("div.container");
    // $el refer to the newl added element
}

Demo: Fiddle 演示: 小提琴

  • use .appendTo() so that it will return the newly created element which can be used for further processing 使用.appendTo(),以便它将返回新创建的元素,该元素可用于进一步处理
for (var i = 0; i < arrayLength; i++) {
  $("div.container").html("<div class='domain-list'></div>");
  $(".domain-list:nth-child("+i+")").html("<p>"+myStringArray[i]+"</p>");
  //Do something
}

Try to use appendTo in jquery 尝试在jquery中使用appendTo

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
  $("<div class='domain-list"+i+"'></div>").html("<p>"+myStringArray[i]+"</p>").appendTo("div.container");
  //Do something
}

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

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