获取输入字段的值并附加到DOM

时间:2016-02-24 05:46:03

标签: javascript dom

我试图将我的输入值附加到DOM。 不知道为什么我没有得到输入框的值。我一直得到[对象HTMLInputElement] ...任何帮助都会很感激。我尝试了几种方法,但仍然没有得到任何结果。

// 'use strict';

var button;
var list = document.getElementById("greatList");
//var item = document.getElementById("addItems").value;
//console.log(item);

document.addEventListener('DOMContentLoaded', init);

function init(){
	 button = document.getElementById('addButton');
	

	document.querySelector('#addButton').addEventListener('click', addField);
	//button.addEventListener('click', getItem)

}

function addField(){
	var item = document.getElementById("addItems").value;
	var newField = document.createElement('li');
	newField.appendChild(document.createTextNode(addItems));
	newField.classList.add('singleLine');
	list.appendChild(newField);
	console.log("working");
}
<div class="wrapper">
	<div class="list">
		<h2>List: </h2>
		<section class="top">

			<input type="text" value="input" id="addItems">
			<button type="submit" id="addButton" onclick="addField()">Add</button>
			<button>Get Random</button>
		</section>
		<hr>
		<section class="result">
			<ul id="greatList">
				<li class="singleLine">Hello</li>
			</ul>
		</section>
	</div>
</div>

这是bin

1 个答案:

答案 0 :(得分:1)

  

addItems

中使用item代替document.createTextNode

addItems是元素的id因此JS解析器将追加<input type="text" value="input" id="addItems">元素。

  

element IDs are global variables

var list = document.getElementById("greatList");
document.addEventListener('DOMContentLoaded', init);

function init() {
  document.querySelector('#addButton').addEventListener('click', addField);
}

function addField() {
  console.log(addItems);
  var item = document.getElementById("addItems").value;
  var newField = document.createElement('li');
  newField.appendChild(document.createTextNode(item));
  newField.classList.add('singleLine');
  list.appendChild(newField);
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div class="wrapper">
  <div class="list">
    <h2>List: </h2>
    <section class="top">

      <input type="text" value="input" id="addItems">
      <button type="submit" id="addButton">Add</button>
      <button>Get Random</button>
    </section>
    <hr>
    <section class="result">
      <ul id="greatList">
        <li class="singleLine">Hello</li>
      </ul>
    </section>
  </div>
</div>

注意:避免绑定inline-events(您有addEventListener以及inline-click-event)所以它会调用两次函数..