亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用javascript從輸入數組創建HTML列表

使用javascript從輸入數組創建HTML列表

喵喵時光機 2021-12-12 16:07:52
雖然我在這里看到了類似的問題和解決方案,但我無法弄清楚我的代碼的問題。有人可以幫忙調查一下并告訴我我做錯了什么。我正在嘗試使用數組函數將用戶輸入添加到列表中。我希望在用戶輸入之前數組中已經有 3 個元素,然后使用另一種數組方法刪除添加的輸入。但首先添加輸入一直是我的挑戰。我已經添加了我的代碼以供查看。    var domTarget = id => {  return document.getElementById(id);};var UnsortedTrees = ["spruce", "pine", "cedar"];let ordered = document.createElement("ol");domTarget("tree-display").appendChild(ordered);UnsortedTrees.forEach(Unsortedtree => {  let listOfTrees = document.createElement("li");  ordered.appendChild(listOfTrees);  listOfTrees.innerHTML += Unsortedtree;});const frontAdd = () => {  console.log(UnsortedTrees);  let userInput = domTarget("array-input").value;  var isValid = true;  if (userInput === "") {    alert("Please enter a tree name");    isValid = false;  }  if (userInput) {    UnsortedTrees.push(userInput);    domTarget("tree-display").reset();    let ordered = document.createElement("ol");    domTarget("tree-display").appendChild(ordered);    UnsortedTrees.forEach(Unsortedtree => {      let listOfTrees = document.createElement("li");      ordered.appendChild(listOfTrees);      listOfTrees.innerHTML += Unsortedtree;    });  }};window.onload = () => {   domTarget("front-add").onclick = frontAdd;};
查看完整描述

2 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

重構你的代碼一點點。這會是你的意思嗎?


(() => {

  const byId = id => document.querySelector(`#${id}`);

  const ordered = byId("treeList");

  const appendListItem = (orderedList, itemTxt) => {

    let listItem = document.createElement("li");

    listItem.textContent = itemTxt;

    orderedList.appendChild(listItem);

  };

  const addItem = () => {

    const inputEl = byId("array-input");

    const val = inputEl.value.trim();

  

    if (!val) { return alert("Please enter a tree name"); }


    UnsortedTrees.push(val);

    appendListItem(ordered, val);

    inputEl.value = "";

  };

  

  // create initial

  let UnsortedTrees = ["spruce", "pine", "cedar"];

  UnsortedTrees.forEach(item => appendListItem(ordered, item));

    

  // add button handling

  byId("addItem").addEventListener("click", addItem);

})();

<div id="tree-display">

  <ol id="treeList"></ol>

</div>

<input id="array-input" type="text" placeholder="type a tree name"> 

<button id="addItem">Add</button>


查看完整回答
反對 回復 2021-12-12
?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

我也做了一點re-factoring?又名playing這可能有幫助/興趣?!


<!DOCTYPE html>

<html>

    <head>

        <meta charset='utf-8' />

        <title>Trees in the Forest</title>

        <style>

            body, body *{ box-sizing:border-box;font-family:monospace }

            #forest{ width:100%; height:50vh;}

            .tree{

                width:50px;

                height:80px;

                margin:0.25rem; 

                background:url(https://png.pngtree.com/element_our/sm/20180527/sm_5b0b21833edb1.png);

                background-size:contain;

                background-repeat:no-repeat;

                background-position:bottom;

                background-color:rgba(0,200,0,0.1)

            }

            ol{ width:100%; margin:1rem auto }

            ol > li{display:inline-block;text-align:center}

        </style>

        <script>

            document.addEventListener('DOMContentLoaded',()=>{


                const domTarget=function(n){

                    return document.getElementById( n );

                };


                /* utility to generate new DOM elements with attributes and value */

                const create=function(t,a,p){

                    let el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );

                    let _arr=['innerHTML','innerText','html','text'];

                    for( let x in a ) if( a.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, a[ x ] );

                    if( a.hasOwnProperty('innerHTML') || a.hasOwnProperty('html') ) el.innerHTML=a.innerHTML || a.html;

                    if( a.hasOwnProperty('innerText') || a.hasOwnProperty('text') ) el.innerText=a.innerText || a.text;

                    if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );

                    return el;

                };


                /* wrapper for rebuilding the OL contents */

                const createforest=function(a,p){

                    p.innerHTML=''; // clear previous content

                    a.sort( ( x, y )=>{ return x > y ? 1 : -1 } ) // sort the array alphabetically

                    a.forEach( tree => { create( 'li',{ text:tree, 'class':'tree', 'data-tree':tree }, p ); } ); // add each tree

                };



                /* The initial collection of trees */

                let trees=[ 'spruce', 'pine', 'cedar' ];




                /* Existing DOM elements */

                let forest=domTarget('forest');

                let bttn=document.querySelector('form > input[ type="button" ]');

                let ol=create( 'ol', {}, forest );




                /* create the initial display of trees */

                createforest( trees, ol );





                /* Listen for button clicks - add new tree to the array and rebuild display */

                bttn.addEventListener( 'click', function(e){

                    let input=this.previousElementSibling;

                    if( input.value!='' ){

                        if( trees.length >= 3 ){

                            /* add to the array */

                            trees.push( input.value );


                            /* rebuild the display */

                            createforest( trees, ol );


                            /* clear the input field */

                            input.value='';

                            input.focus();

                        }

                        return true;

                    }

                    alert( 'Please enter a tree name' );

                });



                /* listenen for clicks on parent container */

                ol.addEventListener('click',(e)=>{

                    if( e.target!=e.currentTarget ){

                        /* remove tree from array and display */

                        let tree=e.target.dataset.tree;

                        trees.splice( trees.indexOf( tree ), 1 );

                        e.target.parentNode.removeChild( e.target );

                    }

                });

            })

        </script>

    </head>

    <body>

        <div id='forest'></div>

        <form>

            <input type='text' />

            <input type='button' value='Add Tree' />

        </form>

    </body>

</html>


查看完整回答
反對 回復 2021-12-12
  • 2 回答
  • 0 關注
  • 279 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號