如何捕获单击功能下的多个按钮并将内容发送到本地存储
2020-05-27
308
编码新手,参加了 Bootcamp 课程 7 周。我尝试使用 Javascript 中的单击功能控制 9 个不同的按钮,但收到错误消息 “未捕获 TypeError:无法读取 null 的属性‘addEventListener’” 。每个按钮都应将文本区域内容发送到 localStorage。从 HTML 代码中可以看出,我尝试使用类“pageMaster”在顶层单击来控制按钮“save9am”。救命!
var controlAll = document.querySelector("pageMaster");
controlAll.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
var clickedItem = document.getElementById("box9").value;
localStorage.setItem("text", clickedItem);
}
if (e.target !== e.currentTarget) {
var clickedItem = document.getElementById("box16").value;
localStorage.setItem("text", clickedItem);
}
if (e.target !== e.currentTarget) {
var clickedItem = document.getElementById("box17").value;
localStorage.setItem("text", clickedItem);
}
e.stopPropagation();
}
<tbody class="pageMaster">
<tr>
<div class = "col-md-2">
<th scope="row" id="9amTime" class="timeOfDay">9:00am</th>
</div>
<div class = "col-md-8">
<td class="event-box"><textarea class="text-box" value="" id="box9"></textarea></td>
</div>
<div class = "col-md-2">
<td class="save-box"><button id="save9am" class="btn btn-outline-secondary saveBtn" type="button"><i
class="far fa-save"></i></button></td>
</div>
</tr>
<tbody>
1个回答
阅读您的问题非常困难,但我怀疑这就是您 想要 使用的:
var container_elem = document.querySelector(".container");
container_elem.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
var input_text = document.getElementById("textinput").value;
console.log('input_text', input_text)
}
}
<div class="container">
<textarea id="textinput"></textarea>
<p>some arbitrary element</p>
<button>a buttin</button>
</div>
Gavin
2020-05-27