将事件侦听器添加到单页应用程序上的程序分配属性

Adding an event listener to a procedurally assigned attribute on a single page application

我正在 JavaScript 中编写没有库的单页笔记应用程序。该应用程序允许用户添加注释,并在输入下方显示一个缩短的表格。

当他们想要查看笔记的全文时,可以单击相关笔记将其展开。

到目前为止,输入的笔记被保存在一个数组中,然后写成一个缩短的版本(在 HTML 列表元素中呈现),它具有分配给它们的数组位置作为 ID(分配索引)变量为数组长度-1,然后将其设置为属性)

查看代码为

  <html lang="en">
    <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 完成,但我不确定如何获取特定点击的列表项的索引,而不是页面上的第一个列表项。

您需要做的就是将事件侦听器添加到 li 元素,然后再将其附加到注释区域。

newLI.addEventListener('click', function(e) {
  let elementId = e.id;
  // any other logic here
})