未捕获的TypeError:无法设置属性' innerHTML'在HTMLFormElement.addItem(script.js:17)的populateList(script.js:22)中为null

时间:2017-05-31 11:51:51

标签: javascript html

我试图修复错误,但它没有发生,它还在说Uncaught TypeError:无法设置属性< innerHTML'在HTMLFormElement.addItem(script.js:17)的populateList(script.js:22)中为null



const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = [];

function addItem(e) {
	e.preventDefault();
	//console.log('Hello');
	const text = (this.querySelector('[name=item]')).value;
	const item = {
		text,
		done: false
	};
	//console.log(item);
	items.push(item);
	populateList(items, itemsList);
	this.reset();
}

function populateList(plates = [], platesList) {
	platesList.innerHTML = plates.map((plate, i) => {
		return `
			<li>
				<input type="checkbox" data-index=${i} id="item${i}" checked />
				<label for="item${i}">${plate.text}</label>
			</li>
		`;
	}).join('');
}

addItems.addEventListener('submit', addItem);
&#13;
<div class="wrapper">
  <h2>LOCAL TAPAS</h2>
  <p></p>
  <ul>
    <li>Loading Tapas...</li>
  </ul>
  <form class="add-items">
    <input type="text" name="item" placeholder="Item Name" required>
    <input type="submit" value="+ Add Item">
  </form>

</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

将班级class="plates"添加到ul代码

&#13;
&#13;
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = [];

function addItem(e) {
	e.preventDefault();
	//console.log('Hello');
	const text = (this.querySelector('[name=item]')).value;
	const item = {
		text,
		done: false
	};
	//console.log(item);
	items.push(item);
	populateList(items, itemsList);
	this.reset();
}

function populateList(plates = [], platesList) {
	platesList.innerHTML = plates.map((plate, i) => {
		return `
			<li>
				<input type="checkbox" data-index=${i} id="item${i}" checked />
				<label for="item${i}">${plate.text}</label>
			</li>
		`;
	}).join('');
}

addItems.addEventListener('submit', addItem);
&#13;
<div class="wrapper">
  <h2>LOCAL TAPAS</h2>
  <p></p>
  <ul class="plates">
    <li>Loading Tapas...</li>
  </ul>
  <form class="add-items">
    <input type="text" name="item" placeholder="Item Name" required>
    <input type="submit" value="+ Add Item">
  </form>

</div>
&#13;
&#13;
&#13;