【问题标题】:Using jQuery to build a link that can be copied and shared使用jQuery构建可复制和共享的链接
【发布时间】:2022-07-06 16:34:39
【问题描述】:

我正在尝试创建一个实用程序来帮助移动用户共享 YouTube 链接并让它在指定时间启动(YouTube 不在他们的移动网站和应用程序中提供此功能)。

用户粘贴他们的链接:

例如https://www.youtube.com/watch?v=rHcQy8jdAGY

然后他们可以将值添加到小时、分钟和秒字段中。

在他们这样做的同时,正在构建最终链接以供他们复制和分享。

最终的链接如下所示:

https://www.youtube.com/watch?v=rHcQy8jdAGY&t=1h1m1s

...因此视频将从 1:01:01 开始。

我已经开始在这个CodePen 中构建我的实用程序。

我不知道如何将 TIME 值(如果以及何时由用户添加)附加到 URL 字段。

当向任何字段添加值时,需要先附加 URL 的 &t= 部分。

虽然 h/m/s 值在 URL 中出现的顺序并不重要,但最好保持它们的顺序。

顺便说一句,我是一个彻头彻尾的黑客,但我通常可以最终搞定这些事情(在一些帮助下)。

【问题讨论】:

标签: javascript jquery onchange


【解决方案1】:

使用URL APIsearchparams

$('#container').on('input', function() {
  const url = new URL($("#link").val());
  let [h, m, s] = $("#time-wrap input").map(function() {
    return this.value.trim()
  }).get()
  let time = "";
  time += h ? `${h}h` : "";
  time += m ? `${m}m` : "";
  time += s ? `${s}s` : "";
  url.searchParams.set("t",time)
  console.log(time,url.toString())
  $('input[name=URL]').val(url.toString());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <input id="link" type="url" placeholder="Paste the link to your video">

  <div id="time-wrap">
    <input placeholder="Hour">
    <input placeholder="Minute">
    <input placeholder="Second">
  </div>

  <input type="text" id="result-field" name="URL" placeholder="" value="Your sharing link will appear here">
  <br />
</div>
<button onclick="copyFunction()">Copy text</button>

【讨论】:

    【解决方案2】:

    这是一种在没有 URL API 的情况下使用 jquery 的方法。 我使用了一个每次更改输入时调用的函数,然后它从输入中获取所有值,将它们存储在一个数组中,如果它为空,则将它们的值设置为 0。 然后通过简单地添加字符串和元素的值(来自数组)来构建链接。

    JS

     /* Get the text field */
      var copyText = document.getElementById("result-field");
      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /* For mobile devices */
      /* Copy the text inside the text field */
      navigator.clipboard.writeText(copyText.value);
      /* Alert the copied text */
      alert("Copied the text: " + copyText.value);
    }
    
    $("input").change(function() {
      let link = $("#link").val();
      let elements = document.getElementById("time-wrap").querySelectorAll("input");
      elements.forEach(el => {
        if(el.value == "") {
          el.value = 0;
        }
      })
      link += "&t=" + elements[0].value + "h" + elements[1].value + "m" + elements[2].value + "s";
      $("#result-field").val(link);
    })
    

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多