如何使用 jQuery 将 src 设置为 iframe?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16971451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:10:44  来源:igfitidea点击:

How do I set the src to an iframe with jQuery?

javascriptjqueryiframesrc

提问by Alex

My iFrame looks like this:

我的 iFrame 看起来像这样:

<iframe id="iframe" name="iframe1" frameborder="0" src=""></iframe>

And my script looks like this:

我的脚本如下所示:

<script type="text/javascript">
    $(document).ready(function() {
    $('#iframe').attr('src',http://google.com);
})
</script>

I've also tried putting quotes around the url:

我也试过在网址周围加上引号:

<script type="text/javascript">
    $(document).ready(function() {
    $('#iframe').attr('src','http://google.com');
})
</script>

But neither is working.

但两者都不起作用。

What am I missing?

我错过了什么?

回答by SLaks

If you look at the browser's error console, you'll see the real problem:

如果您查看浏览器的错误控制台,您会看到真正的问题:

Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

拒绝在框架中显示“ https://www.google.com/”,因为它将“X-Frame-Options”设置为“SAMEORIGIN”。

Google doesn't let you do that.

谷歌不允许你这样做。

回答by rjg132234

<script type="text/javascript">
    $(document).ready(function() {
    $('#iframe').attr('src', 'http://google.com');
})
</script>

Quotes missing on the url.

网址上缺少引号。

回答by ChrisGheen

You're not allowed to load www.google.com in an iFrame. Try it with another url.

您不能在 iFrame 中加载 www.google.com。用另一个网址试试。

Load denied by X-Frame-Options: https://www.google.com/ does not permit cross-origin framing.

Load denied by X-Frame-Options: https://www.google.com/ does not permit cross-origin framing.

回答by user3332446

$("#iframe").attr("src","your url");

this will work fine.

这将正常工作。

回答by Nikola Mitev

Just call the function with Iframe name and desired url

只需使用 Iframe 名称和所需的 url 调用函数

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ( $iframe.length ) {
        $iframe.attr('src',url);   
        return false;
    }
    return true;
}

Ex:

前任:

loadIframe("iframe1","http://yahoo.com");