无法将动态创建的“ p”标签和“ img”标签包装在动态创建的“ div”标签内

时间:2019-01-28 02:14:06

标签: javascript jquery ajax

我正在尝试将图片标签和标题标签包装在div标签内(所有标签都是动态创建的),但出于某种奇怪的原因,它会显示“ TypeError:在Array.forEach中分配给常量variable.at”!有人可以告诉我我在这段代码中做错了什么,如果它不是很多,我也想知道是否有一种方法可以向所有这些动态div或这些div的图像中添加事件侦听器!谢谢...

function loadGoogleAds() {
    var scriptTag = document.createElement('script');
    scriptTag.setAttribute('src', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js');
    scriptTag.setAttribute('type', 'text/javascript');
    scriptTag.setAttribute('async', 'async');
    document.body.appendChild(scriptTag);
}
window.addEventListener("load", loadGoogleAds);
window.onload = function() {
    $.ajax({
            type: "get", 
            dataType: 'jsonp', 
           url:"https://api.themoviedb.org/3/movie/now_playing?api_key=05b5e7574eac47fdf8f2ac12831493c6&language=en-US&page=1", //url to send to 
            contentType: "application/json; charset=utf-8",
            success: function (msg) { 
                 //console.log(msg);

                 msg.results.forEach((e)=>{
    const div = $(`<div id=${e.id}></div>`);
    const title=$(`<p>${e.title}</p>`);
    const img=$(`<img src=https://image.tmdb.org/t/p/w185/${e.backdrop_path}>`);
    //div+='</div>'; // this is what im trying to achieve
    $("#main").append(div);
    $("#main").append(title);
    $("#main").append(img);
});
                       }

});

};
#main
{
  margin-left: 3%;
}


#main>div{
  display: inline-block;
  width: 33%;
  margin-bottom: 10px;
  
}
#main>p
{
  color: red;
  font-size: 150%;

}

#main>img
{
width:10%;

}

2 个答案:

答案 0 :(得分:0)

如果要将项目添加到div,则可以像使用.append(...)一样使用$("#main").append()

div.append(title).append(img); //append title and image to div
$("#main").append(div);        //append div to main

但是,如果您的CSS定义不在p内,则它们与imgdiv不匹配,因此您可能需要修改它们。

window.onload = function() {
  $.ajax({
    type: "get",
    dataType: 'jsonp',
    url: "https://api.themoviedb.org/3/movie/now_playing?api_key=05b5e7574eac47fdf8f2ac12831493c6&language=en-US&page=1",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {

      msg.results.forEach((e) => {
        let div = $(`<div id=${e.id}></div>`);
        let title = $(`<p>${e.title}</p>`);
        let img = $(`<img src=https://image.tmdb.org/t/p/w185/${e.backdrop_path}>`);

        div.append(title).append(img);
        $("#main").append(div);

      });
    }

  });

};
#main {
  margin-left: 3%;
}

#main>div {
  display: inline-block;
  width: 33%;
  margin-bottom: 10px;
}

#main > div > p {
  color: red;
  font-size: 150%;
}

#main > div > img {
  width: 10%;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div id="main"></div>

答案 1 :(得分:0)

查看内联评论:

// Since you are using JQuery, use the document.ready syntax
// which replaces window.onload in your case.
$(function() {
  $.ajax({
     type: "get", 
     dataType: 'jsonp', 
     url:"https://api.themoviedb.org/3/movie/now_playing?api_key=05b5e7574eac47fdf8f2ac12831493c6&language=en-US&page=1", //url to send to 
     contentType: "application/json; charset=utf-8",
     success: function (msg) { 
       msg.results.forEach((e)=>{
        
         // Don't use const if you want to be able to modify the variable later.
         let div = $(`<div id=${e.id}></div>`);
         let title=$(`<p>${e.title}</p>`);
         let img=$(`<img src=https://image.tmdb.org/t/p/w185/${e.backdrop_path}>`);
    
         // Append the title and the img to the new div
         div.append(title);
         div.append(img);
    
         $("#main").append(div); // And then the div to main
        
         // Now that the elements has been made and added to the DOM, you can
         // attach a click event to it easily:
         $(div).on("click", function(){
           // Whatever you need here
           console.clear();
           console.log("You clicked " + e.title);
         });
       });
    }
  });
});
#main { margin-left: 3%; }
#main>div { display: inline-block; width: 33%; margin-bottom: 10px; }
#main > div > p { color: red; font-size: 150%; } /* Your selector was wrong to select the title */
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<div id="main"></div>