javascript - append 到 IFRAME 中的链接 URL

标签 javascript jquery html iframe append

我有一个带有 IFRAME 的页面。 IFRAME 由指向 RSS 文章的新闻源链接组成。我想在每篇文章中 append URL target="_blank",以便每篇文章在新窗口中打开,而不是在 IFRAME 中打开。我不想更改原始新闻源页面的布局或功能,因此我希望在单击时动态 append 到 URL。主页和 IFRAME 页面在同一个域中。任何帮助将不胜感激。

示例代码:

<html>
<head>
</head>
<body>
<iframe src="http://vangopainting.net/painting-tips?tmpl=component"></iframe>
</body>
<html>

如您所见,上面的 URL 提取了一个剥离的 Joomla 页面,仅显示了内容。此 IFRAME 将嵌入到 Facebook 页面中,当用户单击链接时,它会将整个站点嵌入到 IFRAME 中,而不仅仅是文章。我希望通过将 target="_blank" append 到 URL,或者甚至将 ?tmpl=component append 到 URL,以便 Joomla 去除文章以外的所有内容,从而在新窗口中打开它,而不是 IFRAME。

编辑添加: 好的...这是我的代码:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
    $(function() {
        $('iframe').load(function(){
            $('a',$(this).contents()).each(function(){this.href = this.href + "?tmpl=component";});
        });
    });
</script>
</head>
<body>
<iframe src="link.html" width="100%" height="50px" frameborder="0" scrolling="no"></iframe>
<iframe src="http://vangopainting.net/painting-tips?tmpl=component" width="100%" height="100%" frameborder="0" scrolling="no"></iframe>
</body>
</html>

我添加第一个 iframe 只是为了在 Facebook 中进行测试。

link.html中的内容:

<html>
<head>
</head>
<body>
<a href="http://vangopainting.net/painting-tips/508-newest-mobile-app-matches-paint-color-instantly">http://vangopainting.net/painting-tips/508-newest-mobile-app-matches-paint-color-instantly</a>
</body>
</html>

这是页面的直接链接:http://vangopainting.net/fb/tabs/paintingtips/index.html 一切正常。

这是 Facebook 页面的链接:https://www.facebook.com/pages/Van-Go-Painting-Inc/177992368936448?sk=app_366401100043274 第一个 iframe 的 URL 按原样 append ,但第二个 iframe 未受影响。

我不知道为什么这不起作用。

最佳答案

这应该适合你。

$('a',$('iframe').contents()).attr('target','_blank');

简而言之,它获取所有 iframe 的内容,找到它们的 a 标记,并应用适当的 target 属性。

在您的示例中的 head 标记内添加以下(未经测试的)代码片段以达到预期的效果。

<script>
    $(function() {
        $('iframe').load(function(){
            $('a',$(this).contents()).attr('target','_blank');
        });
    });
</script>

上面的代码片段中发生了很多等待事件。

  • 首先,我们等待页面加载 passing a callback function to $ .我们想等待页面加载,以便我们知道我们可以找到我们的 iframe
  • 执行该回调时,我们会找到所有 iframe 并 append 一个不同的回调,以便在它们加载时调用。
  • 这个不同的回调是执行查找 a 标记并修改它们的实际工作的代码片段。

关于javascript - append 到 IFRAME 中的链接 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8965256/

相关文章:

javascript - 使用 Node : protocol when importing Node. js 内置模块时如何修复 eslint 错误

javascript - 是否可以使用 HTML5 音频 API 反转音频?

javascript - 如何使用 JavaScript 将元素添加到 HTML5 代码

php - 检查地址栏并使用 javascript 重定向

jquery - 当向下滚动达到 div 的全高时,使 div 粘在页面底部

jquery - 如何从多个 HTML 元素的特定起点和终点使用 jQuery .wrap()?

html - 使用 knockoutjs 时 Chrome 中的最大长度约束验证异常

javascript - 在 css 中 float 导致元素向下移动但是当 JS 更改 innerHTML 时,它会上升

javascript - 如何在 React Routes 4 之间传递 props

javascript - 侧边栏选项卡和滑动条在切换时不同步