简体   繁体   English

如何在同一iframe中使用target =“ _ blank”在iframe中打开链接?

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

I want to Open links with target=“_blank” and an iframe in the same iframe. 我想使用target =“ _ blank”和同一iframe中的iframe打开链接。 I tried the code below, but it didn't work. 我尝试了下面的代码,但是没有用。 Php solutions are welcome! 欢迎使用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> 

Have you tried simply changing the target attribute? 您是否尝试过简单地更改target属性?

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

Also, Zain Shaikh is quite correct. 另外, Zain Shaikh是非常正确的。 If the source of the iframe is loaded from a different domain, you will not be able to do this from JavaScript. 如果iframe的源是从其他域加载的,则您将无法通过JavaScript执行此操作。

You can still do this server-side, but that's going to be dependent on which language you use. 您仍然可以在服务器端执行此操作,但这将取决于您使用哪种语言。

As far as a native JavaScript solution: 就本机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');
            }
        }
    }
}

I tested the relevant portion at http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html (as described in your question). 我在http://www.htmlcodetutorial.com/linking/_A_TARGET_95y98y108y97y110y107y.html (如您的问题所述)中测试了相关部分。 The test code used was: 使用的测试代码为:

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');
    }
}

which I ran in the console (Google Chrome). 我在控制台(Google Chrome)中运行的。 Code worked as intended. 代码按预期工作。

To re-iterate, if the source of the iframe is loaded from a different domain, you will not be able to do this from JavaScript. 要再次重申,如果iframe的源是从其他域加载的,则您将无法通过JavaScript执行此操作。

To put it another way, unless the domain you are running YOUR code on is also http://www.htmlcodetutorial.com , you will NOT be able to do this in JavaScript. 换句话说,除非您正在运行您的代码的域也是http://www.htmlcodetutorial.com ,否则您将无法在JavaScript中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM