首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否为数组中的每个节点创建新的列表元素(Javascript)?

是否为数组中的每个节点创建新的列表元素(Javascript)?
EN

Stack Overflow用户
提问于 2021-03-06 04:29:11
回答 2查看 101关注 0票数 0

我在DOM Playground上工作,在那里我严格使用Javascript编辑页面的样式(我知道这很低效--这是一个任务)。DOM Playground

在很大程度上,我几乎完成了。我只需要在被注释的无序列表中添加列表元素(我将分享下面的代码)。有一个名为resources的数组,它包含5个具有以下属性的对象-标题、href和innerHTML。

我正在尝试创建一个forEach函数,该函数遍历资源列表,并插入一个列表项(li),其href、title和innerHTML与数组中的对象相同。例如,resources =

代码语言:javascript
复制
    {
        title: "View the source CSS file of the currently-viewed design.",
        href: "css/style.css",
        innerHTML: "View This Design&#8217;s <abbr title=\"Cascading Style Sheets\">CSS</abbr>"
    }

但是我希望第一个列表项看起来像这样:

代码语言:javascript
复制
<li><a href = "css/style.css">View the source CSS file of the currently-viewed design.</a></li>

在JS中可以创建哪些方法或逻辑来为资源数组中的每个节点创建列表项?

我的代码:

代码语言:javascript
复制
/**
 * Use this javascript file to fix the page design and layout. 
 * Reference the index.html comments for complete details.
 */

// 1) Add CSS Properties to the body tag

    let body = document.querySelector('body');

    body.style.fontSize = '10pt';
    body.style.lineHeight = '14pt';
    body.style.color = '#000033';
    body.style.backgroundColor = '#69f';
    body.style.margin = '0';

// 2) Add the .page-wrapper class

    //create reference to outer div
    let div = document.querySelector('div');

    //name that div with the class name 'page-wrapper
    div.classList.add('page-wrapper');

// 3) Add the .summary class

    /*create reference to div class that is inside the section element 
    of the .page-wrapper class*/
    let summary = document.querySelector('.page-wrapper section div');

    //add new class to reference
    summary.classList.add('summary');

// 4) Add the .sidebar class

    //Create reference to aside in the outer div
    let aside = document.querySelector('aside');

    //add new class to reference
    aside.classList.add('sidebar');

// 5) Add these links to the "Resources" <ul>

 let ul = document.querySelectorAll('.zen-resources ul');

//list of urls as objects with three properties: title, href, and innerHTML
let resources = [
    {
        title: "View the source CSS file of the currently-viewed design.",
        href: "css/style.css",
        innerHTML: "View This Design&#8217;s <abbr title=\"Cascading Style Sheets\">CSS</abbr>"
    },
    {
        title: "Links to great sites with information on using CSS.",
        href: "http://www.mezzoblue.com/zengarden/resources/",
        innerHTML: "<abbr title=\"Cascading Style Sheets\">CSS</abbr> Resources "
    },
    {
        title: "A list of Frequently Asked Questions about the Zen Garden.",
        href: "http://www.mezzoblue.com/zengarden/faq/",
        innerHTML: "<abbr title=\"Frequently Asked Questions\">FAQ</abbr> "
    },   
    {
        title: "Send in your own CSS file.",
        href: "http://www.mezzoblue.com/zengarden/submit/",
        innerHTML: "Submit a Design"
    },
    {
        title: "View translated versions of this page.",
        href: "http://www.mezzoblue.com/zengarden/translations/",
        innerHTML: "Translations"
    },
];

//stuff I was trying out: 
resources.forEach(function(ul){
    //create li
    let li = document.createElement('li');

    li.innerHTML = resources;

    //append it to ul
}

)
//more stuff I was trying out: 
// resources.forEach(function(el){
//     //create an li for each node in the resources array

// });

// resources.forEach(function(element){
//     //create new list item
//     document.createElement('li').innerHTML = resources;
// }

// )
代码语言:javascript
复制
/* Remember, you cannot edit this file. Add the properties using JavaScript. */
p {
    font: 10pt/16pt "Trebuchet MS", sans-serif;
    margin-top: 0px;
    text-align: justify;
}

h3 {
    font: bold normal 12pt "Trebuchet MS", sans-serif;
    letter-spacing: 3px;
    margin-bottom: 2px;
    color: #333333;
    text-align: left;
}

a:link {
    font-weight: bold;
    text-decoration: none;
    color: #FF6600;
}

a:visited {
    font-weight: bold;
    text-decoration: none;
    color: #CC0000;
}

a:hover,
a:active {
    text-decoration: underline;
    color: #FF6600;
}


.page-wrapper {
    background: #9cf url(../images/trees.jpg) no-repeat left top;
    padding: 200px 0px 0px 0px;
    margin: 0px auto;
    width: 800px;
    border-left: 2px dashed #fff;
    border-right: 2px dashed #fff;
}

header {
    margin-bottom: 10px;
}

/* using an image to replace text in an h1. This trick courtesy Douglas Bowman, http://www.stopdesign.com/articles/css/replace-text/ */
header h1 {
    background: transparent;
    margin-top: -180px;
    width: 500px;
    height: 87px;
    float: left;
    color: #fff;

    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

header h2 {
    background: transparent url(../images/tag.gif) no-repeat top left;
    width: 300px;
    margin-top: -60px;
    margin-left: -190px;
    height: 100px;
    float: right;

    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

.summary {
    width: 130px;
    float: left;
    padding: 5px;
    margin-right: 15px;
    background: #0099FF;

}

.summary p {
    font: bold 8pt/12pt verdana, sans-serif;
    text-align: right;
    color: #fff;
}

.summary a:link {
    font-weight: bold;
    text-decoration: none;
    color: #003;
}

.summary a:visited {
    font-weight: bold;
    text-decoration: none;
    color: #006;
}

.summary a:hover,
.summary a:active {
    text-decoration: underline;
    color: #FF6600;
}

.preamble,
#supporting text,
.explanation,
.participation,
.benefits,
.requirements {
    padding: 0px 170px 0px 30px;
}

footer {
    text-align: center;
}

footer a:link,
footer a:visited {
    margin-right: 20px;
}

.sidebar {
    background: transparent url(../images/menu.gif) top left no-repeat;
    position: absolute;
    top: 0px;
    padding: 15px;
    margin-top: 200px;
    margin-left: 650px;
    width: 130px;
}

.sidebar .wrapper {
    font: 10px verdana, sans-serif;
    padding-top: 35px;
}

.sidebar h3.select {
    background: transparent url(../images/select.gif) top left no-repeat;
    width: 130px;
    height: 25px;
    margin-left: -8px;

    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

.sidebar h3.archives {
    background: transparent url(../images/archives.gif) top left no-repeat;
    width: 130px;
    height: 25px;
    margin-left: -8px;

    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

.sidebar h3.resources {
    background: transparent url(../images/resources.gif) top left no-repeat;
    width: 130px;
    height: 25px;
    margin-left: -8px;

    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

.sidebar ul {
    margin: 0px;
    padding: 0px;
}

.sidebar li {
    line-height: 2.5ex;
    background: transparent;
    display: block;
    padding-top: 5px;
    margin-bottom: 5px;
    list-style-type: none;
}

.sidebar li a:link {
    color: #FF3300;
}

.sidebar li a:visited {
    color: #FF0000;
}

.extra1 {
    background: transparent;
    position: absolute;
    top: 40px;
    right: 0px;
    width: 148px;
    height: 110px;
}
代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>CSS Zen Garden: The Beauty of CSS Design</title>
    <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.csszengarden.com/zengarden.xml">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Dave Shea">
    <meta name="description" content="A demonstration of what can be accomplished visually through CSS-based design.">
    <meta name="robots" content="all">
    <link rel="stylesheet" href="css/style.css">
</head>

<!-- Add the following styles to the <body> tag below -->
<!-- font: 10pt/14pt "Trebuchet MS", sans-serif; -->
<!-- color: #000033; -->
<!-- background: #69f; -->
<!-- margin: 0px; -->
<body id="css-zen-garden">

    <!-- Add the class "page-wrapper" to the <div> below -->
    <div>

        <section class="intro" id="zen-intro">
            <header role="banner">
                <h1>CSS Zen Garden</h1>
                <h2>The Beauty of <abbr title="Cascading Style Sheets">CSS</abbr> Design</h2>
            </header>

            <!-- Add the "summary" class to the <div> below -->
            <div class="" id="zen-summary" role="article">
                <p>A demonstration of what can be accomplished through <abbr
                        title="Cascading Style Sheets">CSS</abbr>-based design. Select any style sheet from the list to
                    load it into this page.</p>
                <p>Download the example <a href="/examples/index"
                        title="This page's source HTML code, not to be modified.">html file</a> and <a
                        href="/examples/style.css" title="This page's sample CSS, the file you may modify.">css file</a>
                </p>
            </div>

            <div class="preamble" id="zen-preamble" role="article">
                <h3>The Road to Enlightenment</h3>
                <p>Littering a dark and dreary road lay the past relics of browser-specific tags, incompatible <abbr
                        title="Document Object Model">DOM</abbr>s, broken <abbr
                        title="Cascading Style Sheets">CSS</abbr> support, and abandoned browsers.</p>
                <p>We must clear the mind of the past. Web enlightenment has been achieved thanks to the tireless
                    efforts of folk like the <abbr title="World Wide Web Consortium">W3C</abbr>, <abbr
                        title="Web Standards Project">WaSP</abbr>, and the major browser creators.</p>
                <p>The CSS Zen Garden invites you to relax and meditate on the important lessons of the masters. Begin
                    to see with clarity. Learn to use the time-honored techniques in new and invigorating fashion.
                    Become one with the web.</p>
            </div>
        </section>

        <div class="main supporting" id="zen-supporting" role="main">
            <div class="explanation" id="zen-explanation" role="article">
                <h3>So What is This About?</h3>
                <p>There is a continuing need to show the power of <abbr title="Cascading Style Sheets">CSS</abbr>. The
                    Zen Garden aims to excite, inspire, and encourage participation. To begin, view some of the existing
                    designs in the list. Clicking on any one will load the style sheet into this very page. The <abbr
                        title="HyperText Markup Language">HTML</abbr> remains the same, the only thing that has changed
                    is the external <abbr title="Cascading Style Sheets">CSS</abbr> file. Yes, really.</p>
                <p><abbr title="Cascading Style Sheets">CSS</abbr> allows complete and total control over the style of a
                    hypertext document. The only way this can be illustrated in a way that gets people excited is by
                    demonstrating what it can truly be, once the reins are placed in the hands of those able to create
                    beauty from structure. Designers and coders alike have contributed to the beauty of the web; we can
                    always push it further.</p>
            </div>

            <div class="participation" id="zen-participation" role="article">
                <h3>Participation</h3>
                <p>Strong visual design has always been our focus. You are modifying this page, so strong <abbr
                        title="Cascading Style Sheets">CSS</abbr> skills are necessary too, but the example files are
                    commented well enough that even <abbr title="Cascading Style Sheets">CSS</abbr> novices can use them
                    as starting points. Please see the <a href="http://www.mezzoblue.com/zengarden/resources/"
                        title="A listing of CSS-related resources"><abbr title="Cascading Style Sheets">CSS</abbr>
                        Resource Guide</a> for advanced tutorials and tips on working with <abbr
                        title="Cascading Style Sheets">CSS</abbr>.</p>
                <p>You may modify the style sheet in any way you wish, but not the <abbr
                        title="HyperText Markup Language">HTML</abbr>. This may seem daunting at first if you&#8217;ve
                    never worked this way before, but follow the listed links to learn more, and use the sample files as
                    a guide.</p>
                <p>Download the sample <a href="/examples/index"
                        title="This page's source HTML code, not to be modified.">HTML</a> and <a
                        href="/examples/style.css" title="This page's sample CSS, the file you may modify.">CSS</a> to
                    work on a copy locally. Once you have completed your masterpiece (and please, don&#8217;t submit
                    half-finished work) upload your <abbr title="Cascading Style Sheets">CSS</abbr> file to a web server
                    under your control. <a href="http://www.mezzoblue.com/zengarden/submit/"
                        title="Use the contact form to send us your CSS file">Send us a link</a> to an archive of that
                    file and all associated assets, and if we choose to use it we will download it and place it on our
                    server.</p>
            </div>

            <div class="benefits" id="zen-benefits" role="article">
                <h3>Benefits</h3>
                <p>Why participate? For recognition, inspiration, and a resource we can all refer to showing people how
                    amazing <abbr title="Cascading Style Sheets">CSS</abbr> really can be. This site serves as equal
                    parts inspiration for those working on the web today, learning tool for those who will be tomorrow,
                    and gallery of future techniques we can all look forward to.</p>
            </div>

            <div class="requirements" id="zen-requirements" role="article">
                <h3>Requirements</h3>
                <p>Where possible, we would like to see mostly <abbr title="Cascading Style Sheets, levels 1 and 2">CSS
                        1 &amp; 2</abbr> usage. <abbr title="Cascading Style Sheets, levels 3 and 4">CSS 3 &amp;
                        4</abbr> should be limited to widely-supported elements only, or strong fallbacks should be
                    provided. The CSS Zen Garden is about functional, practical <abbr
                        title="Cascading Style Sheets">CSS</abbr> and not the latest bleeding-edge tricks viewable by 2%
                    of the browsing public. The only real requirement we have is that your <abbr
                        title="Cascading Style Sheets">CSS</abbr> validates.</p>
                <p>Luckily, designing this way shows how well various browsers have implemented <abbr
                        title="Cascading Style Sheets">CSS</abbr> by now. When sticking to the guidelines you should see
                    fairly consistent results across most modern browsers. Due to the sheer number of user agents on the
                    web these days &#8212; especially when you factor in mobile &#8212; pixel-perfect layouts may not be
                    possible across every platform. That&#8217;s okay, but do test in as many as you can. Your design
                    should work in at least IE9+ and the latest Chrome, Firefox, iOS and Android browsers (run by over
                    90% of the population).</p>
                <p>We ask that you submit original artwork. Please respect copyright laws. Please keep objectionable
                    material to a minimum, and try to incorporate unique and interesting visual themes to your work.
                    We&#8217;re well past the point of needing another garden-related design.</p>
                <p>This is a learning exercise as well as a demonstration. You retain full copyright on your graphics
                    (with limited exceptions, see <a
                        href="http://www.mezzoblue.com/zengarden/submit/guidelines/">submission guidelines</a>), but we
                    ask you release your <abbr title="Cascading Style Sheets">CSS</abbr> under a Creative Commons
                    license identical to the <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/"
                        title="View the Zen Garden's license information.">one on this site</a> so that others may learn
                    from your work.</p>
                <p role="contentinfo">By <a href="http://www.mezzoblue.com/">Dave Shea</a>. Bandwidth graciously donated
                    by <a href="http://www.mediatemple.net/">mediatemple</a>. Now available: <a
                        href="http://www.amazon.com/exec/obidos/ASIN/0321303474/mezzoblue-20/">Zen Garden, the book</a>.
                </p>
            </div>

            <footer>
                <a href="http://validator.w3.org/check/referer" title="Check the validity of this site&#8217;s HTML"
                    class="zen-validate-html">HTML</a>
                <a href="http://jigsaw.w3.org/css-validator/check/referer"
                    title="Check the validity of this site&#8217;s CSS" class="zen-validate-css">CSS</a>
                <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/"
                    title="View the Creative Commons license of this site: Attribution-NonCommercial-ShareAlike."
                    class="zen-license">CC</a>
                <a href="http://mezzoblue.com/zengarden/faq/#aaa" title="Read about the accessibility of this site"
                    class="zen-accessibility">A11y</a>
                <a href="https://github.com/mezzoblue/csszengarden.com" title="Fork this site on Github"
                    class="zen-github">GH</a>
            </footer>

        </div>

        <!-- Add the "sidebar" class to the <aside> below -->
        <aside class="" role="complementary">
            <div class="wrapper">

                <div class="design-selection" id="design-selection">
                    <h3 class="select">Select a Design:</h3>
                    <nav role="navigation">
                        <ul>
                            <li>
                                <a href="/221/" class="design-name">Mid Century Modern</a> by <a
                                    href="http://andrewlohman.com/" class="designer-name">Andrew Lohman</a>
                            </li>
                            <li>
                                <a href="/220/" class="design-name">Garments</a> by <a href="http://danielmall.com/"
                                    class="designer-name">Dan Mall</a>
                            </li>
                            <li>
                                <a href="/219/" class="design-name">Steel</a> by <a href="http://steffen-knoeller.de"
                                    class="designer-name">Steffen Knoeller</a>
                            </li>
                            <li>
                                <a href="/218/" class="design-name">Apothecary</a> by <a href="http://trentwalton.com"
                                    class="designer-name">Trent Walton</a>
                            </li>
                            <li>
                                <a href="/217/" class="design-name">Screen Filler</a> by <a
                                    href="http://elliotjaystocks.com/" class="designer-name">Elliot Jay Stocks</a>
                            </li>
                            <li>
                                <a href="/216/" class="design-name">Fountain Kiss</a> by <a
                                    href="http://jeremycarlson.com" class="designer-name">Jeremy Carlson</a>
                            </li>
                            <li>
                                <a href="/215/" class="design-name">A Robot Named Jimmy</a> by <a
                                    href="http://meltmedia.com/" class="designer-name">meltmedia</a>
                            </li>
                            <li>
                                <a href="/214/" class="design-name">Verde Moderna</a> by <a
                                    href="http://www.mezzoblue.com/" class="designer-name">Dave Shea</a>
                            </li>
                        </ul>
                    </nav>
                </div>

                <div class="design-archives" id="design-archives">
                    <h3 class="archives">Archives:</h3>
                    <nav role="navigation">
                        <ul>
                            <li class="next">
                                <a href="/214/page1">
                                    Next Designs <span class="indicator">&rsaquo;</span>
                                </a>
                            </li>
                            <li class="viewall">
                                <a href="http://www.mezzoblue.com/zengarden/alldesigns/"
                                    title="View every submission to the Zen Garden.">
                                    View All Designs </a>
                            </li>
                        </ul>
                    </nav>
                </div>

                <div class="zen-resources" id="zen-resources">
                    <h3 class="resources">Resources:</h3>

                    <!-- Add new links to #resourceList -->
                    <!-- Use the values from the "resources" variable in your js file -->
                    <ul id="resourceList">

                    </ul>
                </div>
            </div>
        </aside>


    </div>

    <div class="extra1" role="presentation"></div>
    <div class="extra2" role="presentation"></div>
    <div class="extra3" role="presentation"></div>
    <div class="extra4" role="presentation"></div>
    <div class="extra5" role="presentation"></div>
    <div class="extra6" role="presentation"></div>
    
    <script src="js/fix-the-page.js"></script>
</body>

</html>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-06 04:36:44

如果您的资源列表是一个对象数组,使用与示例中给出的相同的对象形式,则此代码片段将为您提供所需的内容,

代码语言:javascript
复制
const resources = [{
title: "View the source CSS file of the currently-viewed design.",
href: "css/style.css",
innerHTML: "View This Design&#8217;s <abbr title=\"Cascading Style Sheets\">CSS</abbr>"
  },
  {
title: "Links to great sites with information on using CSS.",
href: "http://www.mezzoblue.com/zengarden/resources/",
innerHTML: "<abbr title=\"Cascading Style Sheets\">CSS</abbr> Resources "
  },
  {
title: "A list of Frequently Asked Questions about the Zen Garden.",
href: "http://www.mezzoblue.com/zengarden/faq/",
innerHTML: "<abbr title=\"Frequently Asked Questions\">FAQ</abbr> "
  },
  {
title: "Send in your own CSS file.",
href: "http://www.mezzoblue.com/zengarden/submit/",
innerHTML: "Submit a Design"
  },
  {
title: "View translated versions of this page.",
href: "http://www.mezzoblue.com/zengarden/translations/",
innerHTML: "Translations"
  },
];
     //benchmarking
     const t0 = performance.now()
     //create the container ul element
     const ul = document.createElement('ul');
     //iterate the resources   
     resources.forEach(function(item) {
         //create li element
         const li = document.createElement('li');
         //create anchor element
         const anc = document.createElement('a');
         //set attributes href and innerHTML to anchor
         anc.href = item.href;
         anc.innerHTML = item.innerHTML;
         //set title to the li??
         li.title = item.title;
         //append anchor to li
         li.append(anc);
         //append li to ul
         ul.append(li);
     });
     //finally append everything to the parent node in the DOM, in this case, body
     document.body.append(ul);
     const t1 = performance.now();
     console.log("Creating unordered list took: " + (t1 - t0) + " milliseconds.")

票数 0
EN

Stack Overflow用户

发布于 2021-03-06 04:46:47

编辑:为了满足大家的需求,我更改了我的答案。

尝试一下,创建一个数组并将其添加到ul中(使用.join(''))。

代码语言:javascript
复制
let
    resources = [
    {
        title: "View the source CSS file of the currently-viewed design.",
        href: "css/style.css",
        innerHTML: "View This Design&#8217;s <abbr title=\"Cascading Style Sheets\">CSS</abbr>"
    },
    {
        title: "Links to great sites with information on using CSS.",
        href: "http://www.mezzoblue.com/zengarden/resources/",
        innerHTML: "<abbr title=\"Cascading Style Sheets\">CSS</abbr> Resources "
    },
    {
        title: "A list of Frequently Asked Questions about the Zen Garden.",
        href: "http://www.mezzoblue.com/zengarden/faq/",
        innerHTML: "<abbr title=\"Frequently Asked Questions\">FAQ</abbr> "
    },
    {
        title: "Send in your own CSS file.",
        href: "http://www.mezzoblue.com/zengarden/submit/",
        innerHTML: "Submit a Design"
    },
    {
        title: "View translated versions of this page.",
        href: "http://www.mezzoblue.com/zengarden/translations/",
        innerHTML: "Translations"
    },
],
    liList = [];

resources.forEach(o => {
    liList.push(`<li><a href="${o.href}" title=${o.title}>${o.innerHTML}</a></li>`);
});
document.querySelector('#resourceList').innerHTML = liList.join('');
代码语言:javascript
复制
<ul id="resourceList"></ul>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66499242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档