如何在同一个iframe中打开target=“_blank”的iframe链接

How to open links in an iframe with target=“_blank” in the same iframe?

本文关键字:iframe blank 链接 同一个 target      更新时间:2023-09-26

我想打开target="_blank"和同一iframe中的iframe的链接。我尝试了下面的代码,但没有成功。欢迎使用Php解决方案!

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>

<iframe src="http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html" height="100%" width="100%" ></iframe>
<script>
$('iframe a[target="_blank"]').live('click',function(e){
e.preventDefault(); //stops it opening in a new window
var url = $(this).attr('href');
$('iframe').load(url);
});
</script> 

您是否尝试过简单地更改目标属性?

$('iframe a[target="_blank"]').each(function () {
    $(this).attr('target', '_self');
});

此外,Zain Shaikh是非常正确的。如果iframe的源代码是从另一个域加载的,您将无法从JavaScript中执行此操作。

您仍然可以在服务器端执行此操作,但这将取决于您使用的语言。

就原生JavaScript解决方案而言:

function replaceWithSelf () {
    var iframes = document.getElementsByTagName('iframe');
    var i = 0;
    var j = 0;
    var anchors;
    for (i = 0; i < iframes.length; i += 1) {
        anchors = iframes[i].getElementsByTagName('a');
        for (j = 0; j < anchors.length; j += 1) {
            if (anchors[j].getAttribute('target') === '_blank') {
                anchors[j].setAttribute('target', '_self');
            }
        }
    }
}

我在http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html(如你的问题所述)。使用的测试代码为:

var anchors = document.getElementsByTagName('a');
for (var j = 0; j < anchors.length; j += 1) {
    if (anchors[j].getAttribute('target') === '_blank') {
        anchors[j].setAttribute('target', '_self');
    }
}

我在控制台(谷歌Chrome)中运行了它。代码按预期工作。

要重新迭代,如果iframe的源代码是从另一个域加载的,那么您将无法从JavaScript中执行此操作。

换句话说,除非你运行代码的域也是http://www.htmlcodetutorial.com,您将无法在JavaScript中执行此操作。