首页 > 解决方案 > 生成包含起始 url + document.title + 另一个字符串的可点击 URI

问题描述

我想生成一个可点击的 URL,其中包含一个起始 URL 字符串 + document.title+ 另一个字符串 + response.text。链接文本应为“单击此处”

这是我的代码

<!DOCTYPE html>
<html>

<head>
  <script>
    'use strict';
    var res = "";
    (async () => {
      let response = await fetch('https://httpbin.org/encoding/utf8');

      let text = await response.text(); // read response body as text

      document.getElementById("KK1").innerHTML = (text.slice(0, 10));

      // I want to generate a clickable uri that contains starting url+document.title+another string+response.text. The link text should be "click here"
      document.getElementById("demo").innerHTML = '<a href="https://www.google.com/search?"+ document.title+ "ANOTHER-STRING-HERE"+  text">Click Here</a>';
    })()

  </script>
  <title>My File Dowmloder.rar</title>
</head>

<body>
  <h2>My First Web Page</h2>
  <p>My First Paragraph.</p> Generate clickable URL from parameters. <a id="demo"></a><br>
  <p id="KK1"></p>
</body>

</html>

当我运行此代码时,生成的 URL 仅包含起始 URL 字符串,即“ https://www.google.com/search ?”。但我希望完整的 URL 包含起始 URL + document.title+ 另一个字符串 + response.text

起始网址: https ://www.google.com/search ?
document.title:页面标题
另一个字符串:任何字符串
response.text:从 fetch 接收到的字符串

期待您的帮助。谢谢大家。

标签: javascripthtmlurl

解决方案


我不确定您要做什么,但这会获取内容并建立链接。

fetch('https://httpbin.org/encoding/utf8')
  .then((response) => {
    return response.text();
  })
  .then((text) => {
    document.getElementById("KK1").innerHTML = text.slice(0, 10);
    document.getElementById("demo").href = `https://www.google.com/search?${document.title}another string${text}`;
  });
<html>

<head>
  <title>My File Dowmloder.rar</title>
</head>

<body>

  <h2>My First Web Page</h2>
  <p>My First Paragraph.</p>

  Generate clickable URL from parameters.

  <a id="demo">Click Here</a><br>

  <p id="KK1"></p>
</body>

</html>


推荐阅读