如何正确使用jquery追加

时间:2019-10-30 00:50:57

标签: javascript jquery dom append

我需要根据json文件添加新内容。一旦我在html中手动键入它,它就不会出现问题,但是一旦我想使用jQuery循环,每个函数都将不起作用。注意,我已经检查了使用警报功能的循环方法,它警报2次导致json内容出现2个对象,但似乎与append函数有关。请注意,基于chrome inspect,append函数不会在主div中心内创建div,而是创建每个div并将其单独放置。我是前端开发的菜鸟,对于改进和最佳实践的任何建议都值得赞赏

HTML文件

<div class="wrapper">

 <div class="center"> 
         <div class="column middle"> <p id="text"></p>
             <a href="" id="link">More</a></div>
         <div class="column side">
             <img class="image" id="image" src="">
            </div>
        </div>           
</div>

javascript文件:

info = 
[
  {"details" : "this a text for examples",
   "link" : "www.google.com",
   "image" : "download.jpg"
},
{

    "details" : "this a text for",
    "link" : "www.google.com",
    "image" : "download.jpg"
}
]



$(document).ready(function(){

$.each(info, function(i,v) {
        $(".wrapper").append("<div class=\"center\">");
        $(".wrapper").append("<div class=\"column middle\"> <p id=\"text\" 
         </p>");
        $(".wrapper").append("<a href=\"\" id=\"link\">More</a></div>");
        $(".wrapper").append("<div class=\"column side\">");
        $(".wrapper").append("<img class=\"image\" id=\"image\" src=\"\">");
        $(".wrapper").append("</div>");
        $(".wrapper").append("</div>");

        document.getElementById("text").innerHTML = info[i].details;
        $("#link").attr("href",info[i].link); 
        $("#image").attr("src",info[i].image);
    });

});

4 个答案:

答案 0 :(得分:1)

主要问题是您试图复制id无效。请记住id属性必须是唯一的,因此,如果您确实需要id,则可以附加索引以使其唯一。

此外,您可以使用backticks来保持代码干净,然后使用$.each的第二个参数来获取值,而不是通过它们的索引进行访问。

info = [{
    "details": "this a text for examples",
    "link": "www.google.com",
    "image": "download.jpg"
  },
  {

    "details": "this a text for",
    "link": "www.google.com",
    "image": "download.jpg"
  }
]



$(document).ready(function() {

  $.each(info, function(i, v) {
    $(".wrapper").append(`
       <div class="center">
        <div class="column middle"> 
          <p>${v.details}</p>
          <a href="${v.link}">More</a>
        </div>
        <div class="column side">
           <img class="image" src="${v.image}">
        </div>
      </div>
       `);
  });

});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="wrapper">

  <div class="center">
    <div class="column middle">
      <p id="text"></p>
      <a href="" id="link">More</a></div>
    <div class="column side">
      <img class="image" id="image" src="">
    </div>
  </div>
</div>

答案 1 :(得分:1)

如果使用的是ES6支持的浏览器,则可以使用模板文字。

ES6

let info = [{
  "details": "this a text for examples",
  "link": "www.google.com",
  "image": "download.jpg"
}, {
  "details": "this a text for",
  "link": "www.google.com",
  "image": "download.jpg"
}];

$(() => {
  $('.wrapper').append(info.map(renderContent));
});

function renderContent(data) {
  return `
    <div class="center">
      <div class="column middle">
        <p id="text">${data.details}</p>
        <a href="${data.link}" id="link">More</a></div>
      <div class="column side">
        <img class="image" id="image" src="${data.image}">
      </div>
    </div>
  `;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

ES5或更低

如果您使用的是ES5或更低版本,则可以使用handlebars之类的库。

var info = [{
  "details": "this a text for examples",
  "link": "www.google.com",
  "image": "download.jpg"
}, {
  "details": "this a text for",
  "link": "www.google.com",
  "image": "download.jpg"
}];


$(document).ready(function() {
  var template = Handlebars.compile($("#entry-template").html());
  $('.wrapper').append(info.map(v => template(v)));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.min.js"></script>
<div class="wrapper"></div>

<script id="entry-template" type="text/x-handlebars-template">
  <div class="center">
    <div class="column middle">
      <p id="text">{{details}}</p>
      <a href="{{link}}" id="link">More</a></div>
    <div class="column side">
      <img class="image" id="image" src="{{image}}">
    </div>
  </div>
</script>

或者您可以将模板嵌入for循环中。

var info = [{
  "details": "this a text for examples",
  "link": "www.google.com",
  "image": "download.jpg"
}, {
  "details": "this a text for",
  "link": "www.google.com",
  "image": "download.jpg"
}];

$(document).ready(function() {
  var template = Handlebars.compile($("#entry-template").html());
  $('body').append(template(info));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.min.js"></script>

<script id="entry-template" type="text/x-handlebars-template">
  <div class="wrapper">
    {{#each .}}
      <div class="center">
        <div class="column middle">
          <p id="text">{{details}}</p>
          <a href="{{link}}" id="link">More</a></div>
        <div class="column side">
          <img class="image" id="image" src="{{image}}">
        </div>
      </div>
    {{/each}}
  </div>
</script>

仅适用于jQuery

请注意,我建议不要将相同的ID分配给多个元素。这是DOM / HTML / XML中非常重要的规则。

var info = [{
  "details": "this a text for examples",
  "link": "www.google.com",
  "image": "download.jpg"
}, {
  "details": "this a text for",
  "link": "www.google.com",
  "image": "download.jpg"
}];

$(document).ready(function() {
  $('.wrapper').append(info.map(v => renderContent(v)));
});

function renderContent(data) {
  return $('<div>').addClass('center')
    .append($('<div>').addClass('column middle')
      .append($('<p>').attr('id', 'text').text(data.details))
      .append($('<a>').attr('id', 'link').attr('href', data.link).text('More')))
    .append($('<div>').addClass('column side')
      .append($('<img>').addClass('id').attr('id', 'image').attr('src', data.image)));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

答案 2 :(得分:1)

如果您使用的不是与ES6兼容的浏览器,则可以为每个元素制作一个长字符串,包括适当的对象值:

let info = [{
    "details": "this a text for examples",
    "link": "www.stackoverflow.com",
    "image": "profile.jpg"
  },
  {

    "details": "this a text for",
    "link": "www.google.com",
    "image": "download.jpg"
  }
]

$(document).ready(function() {
  $.each(info, function(i, v) {
    $(".wrapper").append('<div class="center">\
<div class="column middle"> <p>' + v.details + '</p>\
<a href="' + v.link + '" >More</a></div>\
<div class="column side">\
<img class="image" src="' + v.image + '">\
</div>\
</div>');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">

</div>

答案 3 :(得分:1)

尝试在jQuery中使用attr方法添加类 '''$(“。wrapper”)。attr('class','Column side')'''