簡體   English   中英

使用javascript創建嵌套的div

[英]Creating nested divs using javascript

我已經使用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操作。

請確保您的回復包含原因和方式,以及我可以用來更好地理解這一點的任何關鍵字或鏈接。 教一個人釣魚等等。非常感謝你!

我喜歡使用模板文字Array.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>的元素。 小心你的選擇器。

好吧,我在這里寫了一些不同的代碼,我喜歡手動創建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

如果我不得不使用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'));
});

在下面的代碼中,我將展示一種實際可行的方式。 希望它有所幫助,因為與oyu想要完成的相比,它是非常准確的

 $(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(); }); 
 #season { border: 1px solid gray; padding: 10px; } .episode { border: 1px solid gray; min-width: 20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="season"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM