簡體   English   中英

為什么在發生更改后 addEventListener 對標簽 textarea 不起作用?

[英]why addEventListener does not work to the tag textarea after a change occurs?

我創建一個元素作為textarea ,我想獲得change事件,但它從未進入updateDescripton function

async function displayIncompleteTask(task) {
  let newCheckBox = `<div id="${"t"+task._id}"><label for="${task._id}" class="container"><input type="checkbox" name="task" id="${task._id}" onclick = taskCompleted(this.id)><span class="checkmark"></span></label><textarea for="${task._id}" id = "${"i" + task._id}" onchange="updateTask(this.id,this.value)">${task.text}</textarea><button id="${"d" + task._id}" class="descriptionButtons" onclick="displayDescription(this.id)"><i class="fa fa-caret-down" aria-hidden="true"></i></button>  <div id = "${"div-" + task._id}" class="descriptionTextArea"></div></div>`

  document.getElementById("to-do").innerHTML += newCheckBox

  let taskDiv = document.getElementById("div-" + task._id)
  taskDiv.style.display= "none"

  let descriptionTag = document.createElement("textarea")
  descriptionTag.setAttribute("id", "dscp" + task._id)
  descriptionTag.setAttribute("class", "descriptionTextArea")
  descriptionTag.setAttribute("placeholder","Enter your task's description")
  taskDiv.appendChild(descriptionTag)  

  let tag = document.getElementById("dscp" + task._id)
  tag.addEventListener("change", updateDescription)
}

更新說明:

function updateDescription(){
  console.log("Updating")
}

您可以定義updateDescription function,

也不要忘記使用document.body.appendChild(descriptionTag)將 textarea 添加到正文

let descriptionTag = document.createElement("textarea")
  descriptionTag.setAttribute("id", "dscp" + "task._id")
  descriptionTag.setAttribute("class", "descriptionTextArea")
  descriptionTag.setAttribute("placeholder","Enter your task's description")
  descriptionTag.addEventListener("change", updateDescription)
  document.body.appendChild(descriptionTag);
  function updateDescription(){
    console.log(this.value );
  }

 let descriptionTag = document.createElement("textarea") descriptionTag.setAttribute("id", "dscp" + "task._id") descriptionTag.setAttribute("class", "descriptionTextArea") descriptionTag.setAttribute("placeholder","Enter your task's description") descriptionTag.addEventListener("change", updateDescription) document.body.appendChild(descriptionTag); function updateDescription(){ console.log(this.value ); }
 textarea{ width: 100%; height: 50px; }
 <h1>test change event</h1>

因為它是一個文本字段,所以您可以使用Eventlistener並將其與input事件綁定,而不是change ,因此顯然當用戶與文本區域交互時,function 將被觸發。

descriptionTag.addEventListener("input", function(event) {});

但請確保descriptionTag是一個textarea元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM