简体   繁体   English

jQuery创建多个HTML元素而不覆盖旧的HTML

[英]jQuery create multiple HTML elements without overwriting old HTML

I would like to make a dynamic jQuery function that counts the results from the array and than makes for every object in the array an HTML element. 我想制作一个动态jQuery函数,该函数计算数组中的结果,然后为数组中的每个对象创建一个HTML元素。 The array is made by an SharePoint API. 该数组由SharePoint API组成。 So if there are 3 results/objects run the code 3 times. 因此,如果有3个结果/对象,则将代码运行3次。 If there are 2 results/objects run the code 2 times. 如果有2个结果/对象,则将代码运行2次。

With the code below it creates the last result(object) from the array and overwriting the previous made ones. 使用下面的代码,它从数组中创建最后一个result(object)并覆盖之前的结果。

I was thinking about a piece of code that counts the object and then use the append() function to add the HTML fields. 我正在考虑一段计算对象的代码,然后使用append()函数添加HTML字段。 loop it as many times as there are objects. 循环遍历对象的次数。 But not sure this is the best way. 但是不确定这是最好的方法。

jQuery.ajax({
  url: "http://URL/_api/web/webs",
  type: "GET",
  headers: { "accept": "application/json;odata=verbose" },
  success: function (data) {
           console.log(data.d.results);
           var aSites = data.d.results;
           jQuery(aSites).each(function(i,oSite){
               var sTitle = oSite.Title;
               var sURL = oSite.Url;
               console.log(sTitle, sURL);
               jQuery('.wrapper').html(jQuery('<div class="Title"><p>Title:</p><input type="text" name="fname" id="inputTitle"></div><div class="URL"><p>URL:</p><input type="text" name="fname" id="inputURL"></div>'));
               jQuery( "#inputTitle" ).val(sTitle);
               jQuery( "#inputURL" ).val(sURL);
           });
    },
  error: function (error) {
        alert(JSON.stringify(error));
    }
});

You need to use .append() , not .html() , so you add instead of replacing. 您需要使用.append()而不是.html() ,所以您添加而不是替换。 And you can't use the same ID each time, use a class instead. 而且您不能每次都使用相同的ID,而应使用类。

success: function (data) {
   console.log(data.d.results);
   var aSites = data.d.results;
   $('.wrapper').empty();
   jQuery(aSites).each(function(i,oSite){
       var sTitle = oSite.Title;
       var sURL = oSite.Url;
       console.log(sTitle, sURL);
       var newDIV = jQuery('<div class="Title"><p>Title:</p><input type="text" name="fname" class="inputTitle"></div><div class="URL"><p>URL:</p><input type="text" name="fname" class="inputURL"></div>'));
       newDIV.find(".inputTitle" ).val(sTitle);
       newDIV.find(".inputURL" ).val(sURL);
       $('.wrapper').append(newDIV);
   });
},

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

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