首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用用户输入来更改iframe链接上的最后一部分?

如何使用用户输入来更改iframe链接上的最后一部分?
EN

Stack Overflow用户
提问于 2017-04-10 14:21:50
回答 3查看 104关注 0票数 0

我希望用户从提示中输入,以更改iframe网址的最后一部分。到目前为止,我的代码如下:

代码语言:javascript
运行
复制
<!DOCTYPE html>
<html>
  <head>
    <style>
    body{
      background-color:#ffffff
    }
    </style>
  </head>
  <body>
<!-- im attempting to make an iframe display a video the user types into 
the prompt.-->
<p id="Video"></p>

    <script>
      var VideoURL = prompt("type the last part of the YouTube.com video 
URL here");
      if(VideoURL != null){
        document.getElementById("Video").innerHTML= "you typed '' " + 
VideoURL + " '' as your url.";

      } else {
        alert("please reload and type a URL.");
      }
    </script>
<iframe src="www.youtube-nocookie.com/embed/(I WANT THE USERS INPUT 
HERE)" allowfullscreen></iframe>
  </body>
</html>

我已经做了三天了,但还是搞不清楚。请帮帮忙。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-04-10 14:40:57

您只是在脚本的末尾遗漏了一行,它设置了src属性的iframe

代码语言:javascript
运行
复制
<!DOCTYPE html>
<html>
  <head>
    <style>
    body{
      background-color:#ffffff
    }
    </style>
  </head>
  <body>
    <!-- im attempting to make an iframe display a video the user types into 
the prompt.-->
    <p id="video"></p>
    <iframe src="www.youtube-nocookie.com/embed/" allowfullscreen></iframe>
    
    <script>
      // By placing the script just before the end of the <body>, all the DOM elements will
      // have loaded by the time the script runs.
      
      // Get user input:
      var videoURL = prompt("type the last part of the YouTube.com video URL here");
      
      if(videoURL != null){
        // Get a reference to the iframe and reset its src property:
        var frame = document.querySelector("iframe");
        frame.src = frame.src + videoURL;
        
        // Output the new URL
        document.getElementById("video").innerHTML= "New src is: " + frame.src;
      } else {
        alert("please reload and type a URL.");
      }
    </script>
  </body>
</html>

票数 0
EN

Stack Overflow用户

发布于 2017-04-10 14:46:34

可以使用src更改<iframe>的JavaScript属性,我认为这是解决问题的最佳方法。

首先,我建议为您的<iframe>提供一个id,以便于检索。

例如:<iframe id="youtubePlayer" allowfullscreen></iframe>

如果将用户输入存储在变量VideoURL中,则可以使用以下代码行修改<iframe>src

代码语言:javascript
运行
复制
document.getElementById('youtubePlayer').src = "www.youtube-nocookie.com/embed/" + VideoURL;

首先我们使用document.getElementById()检索元素,然后通过给.src赋值来修改源。

我希望这有帮助:)

票数 1
EN

Stack Overflow用户

发布于 2017-04-10 14:37:45

您将不得不通过一个JavaScript变量分配URL的最后一部分,因为当HTML呈现时,页面加载时不会有它。最简单的方法是将ID分配给您的iframe --例如,videoFrame --然后您就可以这样做:

代码语言:javascript
运行
复制
document.getElementById('videoFrame').src = "www.youtube-nocookie.com/embed/" + VideoURL;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43325718

复制
相关文章

相似问题

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