如何迭代数组值并根据这些数组值显示列表对象

时间:2015-10-20 11:22:54

标签: jquery html arrays asp.net-mvc-4

我有一个包含月值的数组对象。我想在“ul”标签下显示这些值。下面是代码:

function LoadPrioritySlider($this, priorityObj) {
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    var monthVal = window.cebMapsApp.cebMapsViewModel.viewModel.MembershipStartMonth()
    var activeMonth = jQuery.inArray(monthVal, months);

    var temp1 = months.slice(0, activeMonth);
    var temp2 = months.slice(activeMonth, months.length)

    months = $.merge(temp2, temp1);

    $this.find(".months-bar").add(months);    
}

我想根据数组值显示“ul”标签和相应的“li”标签。 “months-bar”类包含一个“ul”,而且,我在这个类中添加了相应的月份($ this.find(“。months-bar”)。add(months);)标签,我还添加了“月”。我想将所有月份显示为“li”标签。我将如何实现这一目标。以下是我正在处理的代码。我知道它很容易但是作为jquery的初学者真的让我很难受。关于那个。

<div class="months-bar">
     <ul id="demo">
          <li>A</li>
     </ul>
</div>

1 个答案:

答案 0 :(得分:1)

试试这个,你需要有$.each()循环,你可以在循环中创建一个动态li,每个迭代的文本值,然后追加它:

&#13;
&#13;
function LoadPrioritySlider($this, priorityObj) {
  var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

  var monthVal = "Jul"; //<-----for sake of example
  var activeMonth = jQuery.inArray(monthVal, months);

  var temp1 = months.slice(0, activeMonth);
  var temp2 = months.slice(activeMonth, months.length)

  months = $.merge(temp2, temp1);

  $.each(months, function(i, v) {
    var li = $('<li>',{text:v})
    $('#demo').append(li);
  });

}
LoadPrioritySlider()
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="months-bar">
  <ul id="demo">
  </ul>
</div>
&#13;
&#13;
&#13;