我有一個“保存”按鈕。
單擊“保存”按鈕我在 JS 中創建了一個動態按鈕。
動態按鈕的名稱由變數的值格式化。
我將新動態按鈕的 ID 屬性設定為等于前一個變數的值。
當我單擊新的動態按鈕時,它可以作業。它列印附加到它的變數的值。
問題:當我創建第二個動態按鈕時,該按鈕也可以作業。但是前一個按鈕不再起作用,由于某種原因它列印了變數的新值。
function saveNewProject(){
userProject ;
titleInputValue = document.getElementById("rightBottomContainerContentContainerContent1ElementId").value;
newElement = document.createElement("button");
newElement.setAttribute("type", "button");
newElement.setAttribute("id", userProject);
console.log(newElement);
newElement.innerText = `${userProject} - ${titleInputValue}`;
console.log(newElement);
oldElement = document.getElementById("leftBottomContainerContentContainerContentElementId");
oldElement.appendChild(newElement);
newElementLine = document.createElement("br");
oldElement.appendChild(newElementLine);
console.log(newElement);
newElement.addEventListener("click", function(){
asd = newElement.getAttribute("id");
console.log(asd);
console.log(newElement);
});
}
我是網站開發的新手,這是我的第三天。提前謝謝你的幫助。
uj5u.com熱心網友回復:
在事件處理程式中使用“this”
您的代碼中有一個常見的初學者錯誤。每次添加新按鈕時都會更新 newElement。并且所有按鈕事件處理程式都使用最新的值并顯示最后添加的按鈕的“id”。
要使其作業,您需要更改如下所示的代碼行。它使用“this”而不是 newElement。在事件處理程式中,“this”表示事件附加到的元素。所以 this.id 回傳自身的 ID,而不是最后添加的按鈕的 ID。
嘗試代碼片段,看看它是如何作業的。
// asd = newElement.getAttribute("id"); // <-- incorrect
asd = this.getAttribute("id"); // <-- correct
let userProject = 0;
function saveNewProject(){
userProject ;
titleInputValue = document.getElementById("rightBottomContainerContentContainerContent1ElementId").value;
newElement = document.createElement("button");
newElement.setAttribute("type", "button");
newElement.setAttribute("id", userProject);
console.log(newElement);
newElement.innerText = `${userProject} - ${titleInputValue}`;
//console.log(newElement);
oldElement = document.getElementById("leftBottomContainerContentContainerContentElementId");
oldElement.appendChild(newElement);
newElementLine = document.createElement("br");
oldElement.appendChild(newElementLine);
//console.log(newElement);
newElement.addEventListener("click", function(){
// asd = newElement.getAttribute("id"); // <-- incorrect
asd = this.getAttribute("id"); // <-- correct
console.log("You clicked button " asd);
//console.log(newElement);
});
}
<div id="leftBottomContainerContentContainerContentElementId" value="left">
<input id="rightBottomContainerContentContainerContent1ElementId" value="title" />
<button onclick="saveNewProject()">Save</button>
<br/>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/456482.html
標籤:javascript css 变量 元素 创建元素
