【问题标题】:Get id from URL using JavaScript使用 JavaScript 从 URL 获取 id
【发布时间】:2019-12-13 15:52:49
【问题描述】:

我想使用 JavaScript 从以下 URL 获取视频 ID,然后将其插入 iframe:

示例网址:

http://test.com/dd.php?video=123

示例 iframe:

<iframe frameborder="0" width="640" height="432" 
src="https://www.dailymotion.com/embed/video/insert id here></iframe>

我想在 iframe 中的 dailymotion URL 末尾添加视频 ID。 iframe 中的 src 应如下所示:

src="https://www.dailymotion.com/embed/video/123

在 PHP 中会这样做,但我需要在 JavaScript 中解决它:

<?php echo $_Get["video"]; ?> 

【问题讨论】:

    标签: javascript video iframe


    【解决方案1】:

    使用 JavaScript,您可以从 URLSearchParams 获取它:

    const urlParams = new URLSearchParams(window.location.search);
    const videoId = urlParams.get('video');
    

    【讨论】:

      【解决方案2】:

      从当前网址获取婴儿车:

      const videoId = new URL('http://test.com/dd.php?video=123').searchParams.get('video');
      

      然后将其插入到 iframe 标签中

      const iframe = document.querySelector('iframe');
      
      // split url by "/" to have array of url parts
      const url = iframe.getAttribute('src').split('/');
      
      // update last element to new id
      url[url.length - 1] = videoId;
      
      // set new url to iframe src attribute
      iframe.setAttribute('src', url.join('/'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        相关资源
        最近更新 更多