【问题标题】:Creating a new element with javascript用 javascript 创建一个新元素
【发布时间】:2017-09-24 01:58:02
【问题描述】:

我正在尝试使用文本输入创建一个新的li 元素。问题是当文本出现时,它并没有创建一个我可以设置样式的实际 li 元素。文本在那里,但它只是在一行中彼此相邻。这是我的html:

const button = document.getElementById('submit');

button.addEventListener ("click", () => {
  var taskInput = document.getElementById('task').value;
  // Creating the text for list item.
  if (taskInput === '') { // Prevents empty list item.
    alert("You have to type a task!");
  } else {
  var listItem = document.createElement("li"); // Create li element.
  var text = document.createTextNode(taskInput); // Create text for list item.
  listItem.appendChild(text); // Append text to li element.
  }
  
  //Add new list item to list
  var list = document.getElementById("list");
  list.appendChild(text);
  
});

 
<body>
<h1>Start your list!</h1>
<div class="input">
<input type="text" id="task">
<button id="submit">Create</button>
</div>
<section id="list">
</section>
</body>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    只需使用&lt;ul&gt; 而不是&lt;section&gt; 并附加到listeItem 而不是text。

    const button = document.getElementById('submit');
    
    button.addEventListener ("click", () => {
      var taskInput = document.getElementById('task').value;
      // Creating the text for list item.
      if (taskInput === '') { // Prevents empty list item.
    alert("You have to type a task!");
      } else {
      var listItem = document.createElement("li"); // Create li element.
      var text = document.createTextNode(taskInput); // Create text for list item.
      listItem.appendChild(text); // Append text to li element.
      }
    
      //Add new list item to list
      var list = document.getElementById("list");
      list.appendChild(listItem);
    
    });
    <body>
    <h1>Start your list!</h1>
    <div class="input">
    <input type="text" id="task">
    <button id="submit">Create</button>
    </div>
    <ul id="list">
    </ul>
    </body>

    【讨论】:

      【解决方案2】:

      您正在附加text,您需要附加listItem。看看这个:

      您的代码:

      list.appendChild(text);
      

      应该如何:

      list.appendChild(listItem);
      

      最好的!

      【讨论】:

        【解决方案3】:

        &lt;section&gt;:用于将不同的文章分组为不同的目的或主题,或定义单个文章的不同部分。 ref for more info

        您可以将创建的列表元素添加到此&lt;section&gt; &lt;ol&gt; &lt;li&gt; tags 的不同可能位置,如下所示。

        var listItem = document.createElement("li"); // Create li element.
        listItem.innerHTML = `taskInput`;
        
        var list = document.getElementById("sectionlist");
        list.appendChild(listItem);
        

        const button = document.getElementById('submit');
        button.addEventListener ("click", () => {
        	var taskInput = document.getElementById('task').value;
        
        	if (taskInput !== '') {
        		var listItem = document.createElement("li"); // Create li element.
        		listItem.innerHTML = taskInput;
        
        		var val = $("input[name='Radios']:checked").val();
            
        		var list = document.getElementById("sectionlist");
        		// https://stackoverflow.com/a/13166249/5081877
        		var listCount = $("#sectionlist li").length;
        		var xpath = '//section/ol/li['+listCount+']';
        		if( val == "Option 1") {
             		list.appendChild(listItem);
        		} else if ( val == "Option 2" ) {
        			var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
        			list.insertBefore(listItem, element);
        		} else if ( val == "Option 3" ) {
        			// https://stackoverflow.com/a/2470148/5081877
        			var newElem = new XMLSerializer().serializeToString(listItem);
        			list.insertAdjacentHTML('afterbegin', newElem);
        		}
        	} else {
        		alert("You have to type a task!");
        	}
        });
        body {margin: 2em; font-family: Arial, Helvetica, sans-serif;}
        span {
            /* style this span element so we can display nicely, this stlying is not neccessary */
            margin: 10px 0;
            display: block;
            width: 100%;
            float: left;
        }
        
        input[type="radio"] {
            /* hide the inputs */
            opacity: 0;
        }
        
        /* style your lables/button */
        input[type="radio"] + label {
            /* keep pointer so that you get the little hand showing when you are on a button */
            cursor: pointer;
            /* the following are the styles */
            padding: 4px 10px;
            border: 1px solid #ccc;
            background: #efefef;
            color: #aaa;
            border-radius: 3px;
            text-shadow: 1px 1px 0 rgba(0,0,0,0);
        }
        
        input[type="radio"]:checked + label {
            /* style for the checked/selected state */
            background: #777;
            border: 1px solid #444;
            text-shadow: 1px 1px 0 rgba(0,0,0,0.4);
            color: white;
        }
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <body>
        <div id="myFORM">
          <h3>Insert Element into the DOM tree at a specified position.</h3>
          <span>
        	<input id="Radio1" name="Radios" type="radio" value="Option 1" checked="checked">
        	<label for="Radio1">Node.appendChild() - Insert as END Ele.</label>
          </span>
          <span>
        	<input id="Radio2" name="Radios" type="radio" value="Option 2" >
        	<label for="Radio2">Node.insertBefore() - Insert as Last but one Ele.</label>
          </span>
          <span>
        	<input id="Radio3" name="Radios" type="radio" value="Option 3" >
        	<label for="Radio3">Element.insertAdjacentHTML() - Insert as Start Ele.</label>
          </span>
        </div>
        
        <h1>Start your list!</h1>
        <div class="input">
            <input type="text" id="task">
            <button id="submit">Create</button>
        </div>
        
        <section id="list">
          <ol id="sectionlist">
            <li>Default list Data</li>
          </ol>
        </section>
        </body>

        有关插入元素的更多信息,您可以refer my previous post。

        @见

        【讨论】:

          猜你喜欢
          • 2011-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-19
          • 2017-07-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-26
          相关资源
          最近更新 更多