使用javascript

时间:2017-12-11 23:43:09

标签: javascript jquery html dom appendchild

我已经使用javascript成功创建了一个div,它充满了从API收集的数据。我想要获取部分数据(所有来自Episode,SeasonxEpisode等的innerHTML文本)并将其放入包含div中,以便我可以将其隔离为css样式。

这是我的代码,所有内容都在同一个父级中。还有一个图像从episodeDiv中显示的API中提取,但它不包含在此代码段中,因为它不是问题的一部分。

<script>
let savedResponse;

function clickSeason (seasonNum) {

    const currentSeason = savedResponse['season'+ seasonNum];

    $("#episode-list").html("");

    currentSeason.forEach(function(episode){
        const episodeDiv = document.createElement('div');
        $(episodeDiv).addClass("episodeStyle");

        episodeDiv.innerHTML = 
            "Episode: " + episode.title + '<br />' + '<br />' + 
            "SeasonxEpisode: " + episode.episode + '<br />' + 
            "Original Airdate: " + episode.airdate + '<br />'  + 
            " Stardate: " + episode.stardate + '<br />' + 
            episode.summary;

        $('#episode-list').append(episodeDiv);
</script>

您可以在此处看到完整的项目:http://idesn3535-flamingo.surge.sh/Final/index.html

完整的代码在这里:https://github.com/bmaxdesign/idesn3535-flamingo/blob/master/Final/index.html

我尝试了几个版本:

const episodeData = document.createElement('p');
                $(episodeData).addClass("episodeDataStyle");

episodeData.innerHTML = 
                    "Episode: " + episode.title + '<br />' + '<br />' + 
                    "SeasonxEpisode: " + episode.episode + '<br />' + 
                    "Original Airdate: " + episode.airdate + '<br />'  + 
                    " Stardate: " + episode.stardate + '<br />' + 
                    episode.summary;

$("episodeData").appendChild(episodeDiv);

我希望父节点成为episodeDiv,然后我想将episodeData作为具有单独id的子项嵌套到css中。不幸的是,我上面的内容实际上使整个剧集甚至没有显示,我认为这意味着我的附加方式有一些错误。我想我有一些标签混淆或语法错误,或上述所有。我试图避免在我的HTML页面中留下一个空元素,但我也会对这种方法以及如何将文本放在空div中感到困惑。我显然还没有理解DOM操作。

请确保您的回复包含原因和方式,以及我可以用来更好地理解这一点的任何关键字或链接。教一个人钓鱼等等。非常感谢你!

4 个答案:

答案 0 :(得分:2)

我喜欢使用template literalsArray.map来实现您的目标。皮肤猫的方法有很多种,但这种方法非常紧凑和可读。

// map the episode objects into strings of html
var episodeHTMLArray = currentSeason.map(episode => {
    return `
        <div class='episode'>
            Episode: ${episode.title} <br /> <br />
            SeasonxEpisode: ${episode.episode} <br />
            Original Airdate: ${episode.airdate} <br />
            Stardate: ${episode.stardate}<br />
            ${episode.summary}
        </div>
    `
})

// join the array of html into a plain string
$('#episode-list').html(episodeHTMLArray.join(''))

模板文字是反引号而不是引号,它们可以使用语法${varName}在当前范围内呈现任何变量。

另外,我想我应该指出$("episodeData")正在寻找一个看起来像<episodeData></episodeData>的元素。小心你的选择器。

答案 1 :(得分:1)

好吧,我在这里写了一些不同的代码,我喜欢手动创建DOM元素而不是编程,我更喜欢jQuery语法 - 而且当你使用jquery时,它应该不是问题:

        function clickSeason (seasonNum) {

                    const currentSeason = savedResponse['season'+ seasonNum];
                /*empty (remove everything from) the epsiode list div*/
                    $("#episode-list").empty();
            /*declare empty !string! variable for loop, where we can store all the 
            generated divs - this div has to be declared above the FOR loop,
            as we dont want to overwrite it each loop, 
            we want to add something to it each loop*/        
            var ep = "";
            /*loop through current season array/JSON*/
                    for(var i = 0; i<currentSeason.epsiode.length; i++){
                    /*every loop, we add this structure to ep variable*/
                   /*generate div id by variables, in this example, the id will be for
                   first season second episode like ep1-2*/
                      ep+= "<div id='ep"+seasonNum+"-"i+"' class='episodeStyle'>";
                      ep+= "Episode: " + currentSeason.episode[i].title + "<br /><br />"; 
                      ep+= "SeasonxEpisode: " + currentSeason.episode[i].episode + "<br />"; 
                      ep+= "Original Airdate: " + currentSeason.episode[i].airdate + "<br />";
                      ep+= " Stardate: " + currentSeason.episode[i].stardate + "<br />"; 
                      ep+= currentSeason.episode[i].summary;
                      ep+= "</div>";

                    }
            /*loop ended, you can now add it to any other dom element you like*/
                        $('#episode-list').append(ep);
                 }

现在有点理论: $('#myElementID').append(something);将(作为最后一个孩子)添加到具有该ID的确切元素。 $('.myElementCLASS').append(something);将(作为最后一个孩子)附加到给定类的所有元素。 $('div').append(something);将(作为最后一个孩子)添加到DOM中的所有DIV

您也可以将其与

等变量结合使用
var elem="myElementID";

$("#"+elem+"1").append(something);将附加到#myElementID1

答案 2 :(得分:0)

如果我不得不使用jQuery进行模板化,我可能会做类似的事情:

currentSeason.forEach(function(episode){

    let myHtml = '<div class="episodeStyle"> "Episode:" ' + episode.title + '<br />' + '<br />' + '"SeasonxEpisode: "' + episode.episode + '<br />' + '"Original Airdate: "' + episode.airdate + '<br />'  + '" Stardate: "' + episode.stardate + '<br />' + episode.summary + '</div>';

    myHtml.appendTo($('#episode-list'));
});

答案 3 :(得分:0)

在下面的代码中,我将展示一种实际可行的方式。希望它有所帮助,因为它与oyu想要完成的东西相比是非常准确的

&#13;
&#13;
$(document).ready(function() {


  function clickSeason() {

    /*Lets say this is the data you received form your API*/
    let season1 = [{
      title: 'Episode 1',
      episode: 1
    }, {
      title: 'Episode 2',
      episode: 2
    }, {
      title: 'Episode 3',
      episode: 3
    }];


    let seasonSelector = $("#season");
    //This will Help you select the place where you 
    //are going to load your episodes

    let divHolder;
    let mainContent;

    //We iterate through each element in our object array
    season1.forEach(function(episode) {
      //With jquery you can create a div like this. 
      //You also get the jQuery object for that new div. 
      //With this object you can manipulate your new div even further
      divHolder = $("<div class='episode'></div>");
      //You can append data directrly to the div
      divHolder.append("<h4>" + episode.title + "</h4>");
      divHolder.append("<h5>Episode:" + episode.episode + "</h5>");

      //You could create new containers and still be able to manipulate the.
      mainContent = $("<p class='Content'></p>");

      //It could be less performant, but I prefer 
      //appending in sections instead of all in strings.
      mainContent.append("Original Airdate: " + episode.airdate + '<br /><br />');
      mainContent.append("Stardate: " + episode.stardate + '<br /><br />');
      mainContent.append(episode.summary);

      //We append our mainContent div to the divholder
      divHolder.append(mainContent);
      //We append our divHolder to the Season
      seasonSelector.append(divHolder);
    });
  }

  clickSeason();

});
&#13;
#season {
  border: 1px solid gray;
  padding: 10px;
}

.episode {
  border: 1px solid gray;
  min-width: 20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="season">
</div>
&#13;
&#13;
&#13;