我正在用 JavaScript 编写一个没有库的单页笔记应用程序。该应用程序允许用户添加注释,并在输入下方显示一个缩短的表单。当他们想查看笔记的全文时,他们可以单击相关的笔记将其展开。到目前为止,输入的笔记都保存在一个数组中,然后写成一个简短的版本(在 HTML 列表元素中呈现),其中将数组位置分配给它们作为 ID(分配一个索引变量作为数组长度 -1,然后将其设置为属性)视图代码是 <html> <head> <script src='./note.js'></script> <script src='./controller.js'></script> <title>JS Notes</title> </head> <body> <h1 id="title">JS Notes</h1> <textarea id="input"></textarea><br> <button id="create">Create</button> <ul id="note area"></ul> </body> </html>控制器代码是window.onload = function() { var note, createButton; note = new Note; createButton = document.getElementById("create") createButton.addEventListener("click", processNote) function processNote(){ var input, output, index, newLI; input = document.getElementById('input').value; note.addNote(input); index = note.showFullNote().length - 1 document.getElementById('input').value = "" newLI = document.createElement('li'); newLI.setAttribute("id", index) output = input.substring(0,20) newLI.appendChild(document.createTextNode(output + "...")) document.getElementById('note area').appendChild(newLI) }处理票据的模型(function(exports) { function Note() { this._list = new Array; }; Note.prototype.addNote = function(input) { this._list.push(input) }; Note.prototype.showFullNote = function() { return this._list }; exports.Note = Note;})(this);我试图添加一个用于单击列表元素的事件侦听器,并将该元素的 id 作为索引号传递。我认为这可以由 完成getElementsByTag,但我不确定如何获取专门单击的列表项的索引,而不是页面上的第一个列表项。
1 回答

慕斯709654
TA贡献1840条经验 获得超5个赞
您需要做的就是将事件侦听器添加到li元素,然后再将其附加到注释区域。
newLI.addEventListener('click', function(e) {
let elementId = e.id;
// any other logic here
})
添加回答
举报
0/150
提交
取消