[英]Include a variable in my HTML file from a .js file
編輯:感謝大家的幫助。 實際上在 p5 中有一個內置的 function 允許在屏幕上書寫,現在它可以完美運行。
我有一個包含sc
變量的 sketch.js 文件。
我想在我的 index.html 文件中調用sc
變量來顯示它。
我查看了許多帖子和視頻,但它始終只顯示變量位於同一 HTML 文件的<script>
header 中的方法。
如果我的變量在其他文件中,我該怎么做?
文件:(我正在使用 p5 )
function setup() {
createCanvas(400, 400);
//Square variables
sQx = 5;
sQy = 5;
sQs = 20;
speed = 5;
//Rectangle variables
Rx = 300
Ry = 300
Rw = 40
Rh = 70
//Points variable
Px = 300
Py = 300
Ps = 10
//Score variable
sc = 0
}
function draw() {
background(100);
color(255, 204, 0)
square(sQx, sQy, sQs)
color(255, 204, 0)
//Makes the Square move
if (keyIsDown(UP_ARROW)) {
sQy -= speed
} else if (keyIsDown(DOWN_ARROW)) {
sQy += speed
} else if (keyIsDown(LEFT_ARROW)) {
sQx -= speed;
} else if (keyIsDown(RIGHT_ARROW)) {
sQx += speed;
}
//rect(Rx, Ry, Rw, Rh)
//Create the points
square(Px, Py, 10)
// Detect if Square is on the points and change the points place
let d = dist(sQx, sQy, Px, Py)
if (d <= 30) {
let RdX = random(0, 400)
Px = RdX
let RdY = random(0, 400)
Py = RdY
sc = sc + 1
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sketch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="libraries/p5.min.js"></script>
<script src="libraries/p5.sound.min.js"></script>
<script src="sketch.js">
</script>
</head>
<body>
<div id="sc"></div>
<script>
let value = printSc()
document.getElementById("sc").innerHTML = "your score is:" + value
</script>
<div id="sc"></div>
</body>
</html>
我想在屏幕上顯示“sc”值
抱歉,如果可以以不同的方式完成某些事情,我對編碼真的很陌生
您可以將此代碼放在 HTML 文件中的任何位置:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(sc);
</script>
</body>
</html>
你可以試試這個例子嗎?
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
<title>Document</title>
</head>
<body>
<div id="sc"></div>
</body>
<script>
let value = printSc()
document.getElementById("sc").innerHTML = value
</script>
</html>
腳本.js
function printSc() {
// your logic
let d = 20
let sc
if (d <= 30) {
sc = d + 1
}
return sc
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.