是否可以检索 iframe 页面上的所有 href 元素?
意思是,我有一个页面是来自不同站点的页面的 iframing。我在 iframe 中显示的内容包含许多链接(href 标签)。
是否可以向 iframe 内的所有链接添加空白的 TARGET 属性?链接隐藏在许多 div 和表格中,因此我需要能够在许多嵌套表格/div 中递归添加属性。
编辑: 添加了屏幕截图以显示需要删除的额外字符:
最佳答案
如果 iframe src 在同一个域中,您可以使用 document.getElementById("frameID").document 轻松访问它并对其进行操作。
如果是不同的域,您可以考虑将 iframe 链接到您自己域中的脚本,并使该脚本从远程域下载数据并打印出来:)
myHTMLpage.html
<html>
<head>
<title></title>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ifr").load(function () {
var ifr = document.getElementById("ifr")
var anchors = ifr.contentDocument.getElementsByTagName("a");
for (var i in anchors) {
anchors[i].setAttribute("target", "_blank");
}
});
});
</script>
</head>
<body>
<iframe src="myOwnSite.aspx" width="900px" height="600px" id="ifr" ></iframe>
</body>
</html>
myOwnSite.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyOwnSite.aspx.cs" Inherits="MyOwnSite" %>
myOwnSite.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
public partial class MyOwnSite : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write(new WebClient().DownloadString("http://theExternalSiteHere.com"));
}
}
}
关于javascript - 获取 iframe 内的所有链接并添加空白目标属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8890699/