简体   繁体   English

如何追加到元素并多次设置文本

[英]How to append to an element and set text for multiple times

I have a list of elements where I want to create list like structure with the Bootstrap element (example): 我有一个元素列表,我想在其中使用Bootstrap元素创建类似结构的列表(示例):

<div class="list-group">
  <a href="#" class="list-group-item active">
    <h4 class="list-group-item-heading">List group item heading</h4>
    <p class="list-group-item-text">...</p>
  </a>
</div>

I figured that I will do something like: 我想我会做类似的事情:

foreach(element)
{
   $("#ul").append($("<a href='" + element +"'>").text(element));
}


<div class="container">
  <div id="ul" class="list-group">
</div>

This works fine but I am not sure how to do the other nested elements ( <h4> and <p> ) and also set their text property. 这可以正常工作,但是我不确定如何执行其他嵌套元素( <h4><p> )并设置其text属性。 Also is there a cleaner way to do the href part of <a> element ? 还有一种更干净的方法来处理<a>元素的href部分吗? Any hints and tips are appreciated. 任何提示和技巧表示赞赏。

You need to build those elements individually and append them after you've already operated on them: 您需要单独构建这些元素,并在对其进行操作之后附加它们:

foreach(element)
{
  var anchor = $("<a href='" + element +"'>");
  var header = $('<h4>').text('stuff');
  var p = $('<p>').text('More stuff');
  anchor.append(header).append(p);
  $("#ul").append(anchor);
}

As far as the main question goes, Brennan's answer will definitely do the trick. 就主要问题而言,布伦南的答案肯定会成功。 As for another way to do the href in your <a> , check out this post . 至于在<a>执行href的另一种方法,请查看这篇文章

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

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