【问题标题】:How do I add .each results to a <ul>?如何将 .each 结果添加到 <ul>?
【发布时间】:2016-11-20 19:33:20
【问题描述】:

我正在遍历 SharePoint 列表,结果以 JSON 格式传递。这是通过 .each 完成的

然后我使用 if 语句(如果某列数据等于某个短语)将该结果添加到页面上的无序列表中。

我的问题是它只添加了最后一次迭代。如何确保它添加了与我的 if 语句匹配的每个项目?

$.ajax({
    url: "http://site/subsite/project/_api/Web/Lists/getByTitle('SharePoint List')/items",
    type: "GET",
    headers: { "ACCEPT": "application/json;odata=verbose" },
    success: function(data){
        $.each(data.d.results, function(index) { 
        var courseName = $(this).attr('Title'); 
        var courseNumber = $(this).attr('Course_x0020_Number'); 
        var active = $(this).attr('Active'); 
        var courseUrl = $(this).attr('URL'); 
        var trainingGroup = $(this).attr('Training_x0020_Group'); 

            if (trainingGroup == 'Lab') {
                document.getElementById('labListSpan').innerHTML = '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+'</li></ul>';

            }
        });
        },
        error:  function(){
        alert("Failed to query SharePoint list data. Please refresh (F5).");
        }
    });
}
pullTrainingCourses();

【问题讨论】:

  • 旁注,你在重复做$(this)。每次这样做时,您都在创建一个新的 jQuery 对象,这相对昂贵。创建一次,将其存储在 var 中,然后重复使用该 var。
  • 你有一个如何去做的例子吗?我是 jquery 的新手
  • 存储 $(this)?这只是一个 var $this = $(this); 作为每个中的第一件事,然后在你当前正在做的每个地方都使用 $this $(this)
  • 非常有意义 - 立即实施!

标签: javascript jquery loops sharepoint each


【解决方案1】:
document.getElementById('labListSpan').innerHTML = '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+'</li></ul>';

您每次都在替换 innerHTML。而不是 '=' 使用 '+='

【讨论】:

  • 哇 - 如此简单,但在过去的半个小时里,我一直在用头撞墙。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 2018-06-10
  • 2019-09-21
相关资源
最近更新 更多