有办法在字符串中插入变量吗?(html)



我没有学习过任何其他程序语言,今天我开始学习html,我正在制作在谷歌地图上显示随机位置的程序谷歌地图链接是这个和https://www.google.co.kr/maps/@36.3904052127.33146918.09z我想给链接点赞(https://www.google.co.kr/maps/@纬度,经度,18.09z(这个

<!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">
<title>random palce</title>
</head>
<body style="background-color:#FAD0C9;">
<div style="text-align:center">
<strong>
<p style="font-size: 70px; color:#6E6E6D">click the button</p>
</strong>
<script>
var random1 = (Math.floor(Math.random() * (381601797 - 341601796)) + 341601796)/10000000;
document.write( '<p>' + random1 + '</p>' );
var random2 = (Math.floor(Math.random() * (1289677998 - 1262365489)) + 1262365489)/10000000;
document.write( '<p>' + random2 + '</p>' );
</script>
<button onclick="location.href='https://www.google.co.kr/maps/'
" style="width: 350px; height: 150px; font-size: 40px; background-color:#D64161; color:#364b44; border:none; ">random place</button>
</div>
</body>

这是我编写的代码我想编辑<button onclick=";位置。href='https://www.google.co.kr/maps/'这部分显示链接(https://www.google.co.kr/maps/@纬度,经度,18.09z(

首先,onclick事件是Javascript,而不是html。

然后,您可以使用Template文字在字符串或url中插入变量。此外,我不建议您在onclick中编写长的Javascript代码。请改用脚本中的addEventListener

模板文字是用backtick(`(分隔的文字,允许嵌入称为替换的表达式。

*我真的不知道谷歌地图的请求url格式应该是什么样子,但直接写坐标似乎是错误的。你必须自己想办法。

var random1 = (Math.floor(Math.random() * (381601797 - 341601796)) + 341601796) / 10000000;
document.write('<p>' + random1 + '</p>');
var random2 = (Math.floor(Math.random() * (1289677998 - 1262365489)) + 1262365489) / 10000000;
document.write('<p>' + random2 + '</p>');
document.querySelector('button').addEventListener('click', function() {
location.href = `https://www.google.co.kr/maps/${random1+random2}`
})
<!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">
<title>random palce</title>
</head>
<body style="background-color:#FAD0C9;">
<div style="text-align:center">
<strong>
<p style="font-size: 70px; color:#6E6E6D">click the button</p>
</strong>
<button style="width: 350px; height: 150px; font-size: 40px; background-color:#D64161; color:#364b44; border:none; ">random place</button>
</div>
</body>

最新更新