将 Javascript 数组添加到编号列表 [英] Adding a Javascript Array To a Numbered List

查看:28
本文介绍了将 Javascript 数组添加到编号列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预定义的数组列表,需要将其格式化为 HTML 中的编号列表.我对使用 javascript 的 html 非常陌生,并且在 dom 操作方面遇到了困难

这是我的 js 代码 varfruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];

这是我的 html

<h3>水果</h3>

`

它非常简单,这只是因为我不知道从哪里开始.

解决方案

您可以像下面那样使用 DOM.此代码循环遍历您的数组,并将每个元素添加到有序列表中.

varfruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];var listOfFruits = [];var list = document.getElementById("list");水果.forEach(功能(元素){listOfFruits.push("
  • " + element + "
  • ");});list.innerHTML = listOfFruits.join('');

    <ol id="list"></ol>

    或者你可以像下面那样使用 jQuery.此代码遍历您的数组并将

  • 附加到您的 html.

    varfruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];var listOfFruits = [];水果.forEach(功能(元素){listOfFruits.push("
  • " + element + "
  • ");});$("#list").html(listOfFruits.join(''));

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ol id="list"></ol>

    I have a predefined array list that I need to be formatted into a numbered list in HTML. I'm very new to html with javascript and am having a hard time with dom manipulation

    here is my js code var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];

    here is my html

    <div id="fruits">
    
    
    
            </div>
    
                <h3>Fruits</h3>
    

    `

    its very bare bones and that's simply because I have no idea where to start.

    解决方案

    You can use DOM like below. This code loops through your array, and adds each element to an ordered list.

    var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];
    var listOfFruits = [];
    var list = document.getElementById("list");
    
    
    fruits.forEach(function(element) {
      listOfFruits.push("<li>" + element + "</li>");
    });
    
    list.innerHTML = listOfFruits.join('');

    <ol id="list"></ol>

    Or you can use jQuery like below. This code loops through your array and appends a <li> to your html.

    var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];
    var listOfFruits = [];
    
    
    fruits.forEach(function(element) {
      listOfFruits.push("<li>" + element + "</li>");
    });
    
    $("#list").html(listOfFruits.join(''));

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ol id="list"></ol>

    这篇关于将 Javascript 数组添加到编号列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆