簡體   English   中英

訪問 DOM 加載后附加的元素

[英]Access an element appended after DOM has loaded

我在 DOM 加載后創建了一個輸入框和一個提交按鈕,但在附加后我似乎無法訪問它們

textInput = document.createElement('input');

textInput.setAttribute("id", "myMessage");
textInput.setAttribute("type", "text");
textInput.setAttribute("name", "message");

submitButton = document.createElement('input')

submitButton.setAttribute("id", "sendbutton");
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("name", "submit");
submitButton.setAttribute("value", "Send");

document.getElementById("msgInput").append(textInput)
document.getElementById("msgInput").append(submitButton)

我試圖以這種方式訪問它以捕獲事件keypresskeyuponclick

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById("myMessage").addEventListener('keypress', handleKeyPress);
    document.getElementById("myMessage").addEventListener('keyup', handleKeyUp);

    document.querySelector('#sendbutton').onclick = () => {
        var data = {'msg': document.querySelector('#myMessage').value, 'username': username };
        append_msgs(data);
        document.querySelector('#myMessage').value = '';
    }
});

在 function 中嘗試console.log(document.querySelector('#myMessage')) ,看看會返回什么。 雖然它不能解決您的問題,但它可能會幫助您使用檢查器工具(Chrome 中的F12 )控制台來找出發生了什么。 您是否嘗試過使用getElementById而不是querySelector進行測試?

暫無
暫無

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

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