首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法在字符串中插入变量?(html)

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

Stack Overflow用户
提问于 2022-01-12 16:53:03
回答 1查看 97关注 0票数 0

我没有学习任何其他的程序语言,我今天开始学习html,我正在制作一个程序,在google地图上显示随机位置,google地图链接就是这个,https://www.google.co.kr/maps/@36.3904052,127.331469,18.09z我会给出链接,比如(https://www.google.co.kr/maps/@latitude,longitude,18.09z)这个。

代码语言:javascript
复制
<!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>

这是我编写的代码,我想编辑https://www.google.co.kr/maps/’这一部分显示链接像(https://www.google.co.kr/maps/@latitude,longitude,18.09z)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-12 17:01:17

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

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

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

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

代码语言:javascript
复制
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}`

})
代码语言:javascript
复制
<!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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70685378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档