我正在尝试将ID设置为使用JavaScript创建的元素。但是,当我运行代码时,我只会收到以下错误消息:



我在这里进行了研究,几乎可以说,如果要向创建的元素之一添加ID属性,则必须使用setAttribute("id", "whatever-else-here"),但是会收到一条错误消息,指出它不是函数?

$(document).ready(function() {
    game.start();
});

var
game = {
    start: function() {
        logMessage("Welcome to the Arena!");
        logMessage("Select your Fighter.");
        var dwarfButton = chatbox.appendChild(document.createElement("button")).textContent = "DWARF";
        dwarfButton.setAttribute("id", "dwarf");
    },

最佳答案

您的问题在于以下几行:

var dwarfButton = chatbox.appendChild(document.createElement("button")).textContent = "DWARF";
dwarfButton.setAttribute("id", "dwarf");

您在这里有一些联系,但是最终您将dwarfButton变量设置为字符串"DWARF",而不是您创建的DOM元素。

尝试以下方法:
var dwarfButton = document.createElement("button");
dwarfButton.textContent = "DWARF";
dwarfButton.setAttribute("id", "dwarf");
chatbox.appendChild(dwarfButton);

09-11 10:16