I want to inject text into a div using a variable. Here's a Stack Snippet of my code:
tDNA() { var dna = prompt("Enter the DNA: "); } document.getElementById("dna").innerHTML = "DNA: " + dna;
<!DOCTYPE html> <html> <head> </head> <body> <src="main.js"> <div id="dna"></div> </body> </html> function promp
您需要像这样导入脚本
<script type="text/javascript" src="main.js"></script>
Like this, you have to add the data to the HTML where the variable dna
is in scope and then actually call the function
function promptDNA(){ var dna = prompt("Enter the DNA: "); document.getElementById("dna").textContent = "DNA: " + dna; } promptDNA()
<!DOCTYPE html> <html> <head> </head> <body> <div id="dna"></div> <script src="main.js"></script> </body> </html>
Also, you're importing your script improperly.
You can try this out.
HTML
<html>
<head>
</head>
<body>
<script defer src = "main.js"></script>
<div id = "dna">
<p></p>
</div>
</body>
</html>
JavaScript
function promptDNA(){
var dna = prompt("Enter the DNA: ");
d1 = document.querySelector("p");
d1.textContent = dna;
}
promptDNA();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.