[英]How to open links in an iframe with target=“_blank” in the same iframe?
我想使用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>
您是否嘗試過簡單地更改target屬性?
$('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');
}
}
我在控制台(Google Chrome)中運行的。 代碼按預期工作。
要再次重申,如果iframe的源是從其他域加載的,則您將無法通過JavaScript執行此操作。
換句話說,除非您正在運行您的代碼的域也是http://www.htmlcodetutorial.com ,否則您將無法在JavaScript中執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.