簡體   English   中英

如何在 JavaScript 中為創建的元素添加 ID?

[英]How to add an ID onto a created element in JavaScript?

我原來的問題被另一個用戶錯誤地標記為重復,但提供的鏈接沒有回答問題的任何部分,所以我會問另一個。 制作站點構建器我遇到了一個問題,即按下 OK 時的提示值未用作創建的h1的文本。 為什么是這樣? 該類應用並創建了我想要的所有元素,但網站上根本不存在文本,並且代碼中沒有錯誤,因為一切正常。

 .new-hd { position: fixed; z-index: 5; bottom: 0; right: 0; } .new-para { position: fixed; z-index: 5; bottom: 0; left: 0; } .classic-hd { max-width: 100vw; width: 100vw; max-height: 15vh; height: 15vh; position: absolute; left: 0; top: 0; background-color: black; display: flex; align-items: center; } #classic-hd-txt { color: white; font-family: sans-serif; text-indent: 3vw; } .fa-times { color: white; position: absolute; top: 0.25vh; right: 1vw; z-index: 5; }
 <!DOCTYPE html> <html> <head> <title>Make a Site</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> </head> <body> <button type="button" class="new-hd"> Make Header </button> <button type="button" class="new-para"> Make Paragraph </button> <script> $(document).ready(function() { $(".new-hd").click(function() { var newHdTxt = window.prompt("What would you like your Header Text to be?", "Enter Response Here"); var newHdCont = document.createElement("header"); var newHd = document.createElement("h1"); $(newHdCont).addClass("classic-hd"); $(newHd).addClass("classic-hd-txt"); document.getElementsByClassName("classic-hd-txt").innerHTML = newHdTxt; document.body.appendChild(newHdCont); newHdCont.appendChild(newHd); //alert(newTxt); }); $(".new-para").click(function() { document.createElement("p"); }); }); </script> </body> </html>

代表給出答案的 Nik,這是您解決此問題的方法。 而不是使用 DOM 選擇器get.ElementsByClassName().innerHTML使用方法newHd.innerText = newHdTxt

使用 attr 函數添加 id 屬性。像這樣

$jqueryElement.attr('id', 'change_it_to_what_you_want_but_should_be_unique');

暫無
暫無

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

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