我正在嘗試使用純 JavaScript 創建一個單頁待辦事項應用程式。頁面上有一個按鈕,它從文本框中獲取文本值并使用該輸入值創建一個按鈕。我想要做的是將用戶動態創建的按鈕的文本值傳遞給另一個元素,例如 h2 元素。這是解釋我的意思的螢屏截圖;

輸入串列名稱,然后單擊創建串列按鈕;

使用輸入文本值創建一個按鈕。現在,當您單擊 List 1 按鈕時,該按鈕的文本值“List 1”應傳遞給右側的 h2 元素;

到目前為止,這是我的代碼;
<div class="container" id="table-and-list-names">
<div class="row">
<div class="col-3">
<ul class="nav flex-column" id="list-names">
<!--Names of Lists created by user will be here-->
</ul>
</div>
<!--TABLE-->
<div class="col-9">
<h2 id="current-list-name">Select Todo List</h2>
//...
創建按鈕;
export function createButton(listName) {
const listOfLists = document.querySelector('#list-names');
const newList = document.createElement('li');
const newListButton = document.createElement('button');
newListButton.classList.add("btn", "btn-sm", "btn-outline-primary", "created-list");
newListButton.innerText = listName;
newList.appendChild(newListButton);
listOfLists.appendChild(newList);
}
我試圖用這段代碼傳遞文本值但沒有用;
const currListName = document.querySelector('#current-list-name');
var buttons = document.getElementsByClassName('.created-list');
var buttonCount = buttons.length;
for (var i = 0; i <= length; i)
buttons[i].onClick = function(e) {
currListName.textContent = buttons[i].textContent;
};
單擊按鈕時沒有任何反應,瀏覽器控制臺上沒有錯誤。我只在重繪 頁面時收到錯誤訊息,它顯示“未捕獲的 TypeError:無法訪問屬性“onClick”,按鈕 [i] 未定義”。我認為這是因為重繪 頁面時沒有按鈕。有什么建議么?
uj5u.com熱心網友回復:
那么這個 newListButton 應該如何知道必須做什么呢?您必須通過附加 eventListener 或創建 onlick 處理程式來告訴他。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481765.html
標籤:javascript html dom 支配权
上一篇:如何在多對一關系中映射列舉
