我需要创建一个链接来打开一个页面,并在该页面上的 iframe 中设置一个新目标,这可能吗?
举个例子。
"Link1"必须链接到"索引.html"这个页面上已经有一个 iframe,但是当"index.html"加载时,我需要"仓鼠.html"在 iframe 中加载。
还将有一个
"Link2"和"Link3"也将链接到"索引.html但是"link2"将在iframe中加载页面"兔子.html",而"link3"将在iframe中加载页面"沙鼠.html"。iframe 仍然位于"index.html"中。
我希望这很清楚,我的原始链接代码,示例中的"link1"位于下面。
谢谢
<td onclick="window.location = 'index.html';" style='cursor: hand; cursor: pointer;' background="images/static.gif" id="td1" width="25%" bgcolor="#FFFFFF">
Magnus Engdal是正确的,但你可以使URL获取代码变得容易得多。使用哈希而不是查询字符串,以便将数据 iframe 更改为:
<td class="link" data-iframe="index.html#hamsters.html"></td>
<td class="link" data-iframe="index.html#rabbits.html"></td>
在新页面上,您可以执行以下操作:
$("#iframe").attr("src", window.location.hash);
做。节省大量代码(以及带宽和速度)。
顺便说一句,不要忘记将此代码添加到第一个网页:
$(function () {
$('.link').click(function () {
window.location.href = $(this).data('iframe');;
});
});
让我从这个开始:
不要内联样式!也;
不要内联Javascript!
然后,更多相关信息,您可以按照下面的代码执行一些操作。只需将 data 属性添加到您想要的任何元素(除非您使用锚点,否则在这种情况下您应该熟练使用代码),它就会起作用:
<div data-link="index.html">Click me for index</div>
<label data-link="index2.html">Click me for index2<label>
Javascript:
$(document).ready(function(){
// Use jQuery to select all element with the 'data-link' attribute
$('[data-link]').on('click', function(e){ // add a click eventlistener to it
e.preventDefault(); // this is optional, prevent what it normally would do
$('#iframe')[0].src = $(this).data('link'); // set the iframe to the value of the attribute
});
});
另一方面,这不是要走的路:)使用 PHP 和一些方便的网址:
<a href="index.php?page=gerbils">Gerbils</a>
<a href="index.php?page=hamsters">hamsters</a>
并编制索引.php切换页面。有很多简单的例子可以告诉你如何做到这一点。现在是 2014 年,除非你有充分的理由,否则不要使用 iframe。
这将允许您有一天切换到漂亮的网址:
<a href="/gerbils">Gerbils</a>
<a href="/hamsters">hamsters</a>
如果我理解正确,您想重定向到 iframe 所在的另一个页面。由于其他答案都无法解决此问题,因此您可以将 iframe 目标作为查询字符串发送。
下面是一个示例:
在原始页面上
.HTML
<td class="link" data-iframe="hamsters.html"></td>
<td class="link" data-iframe="rabbits.html"></td>
.JS
$(function () {
$('.link').click(function () {
window.location.href = "index.html?iframe=" + $(this).data('iframe');;
});
});
当您单击原始页面上带有类link
的 <td>
元素时,您将被重定向到 index.html?iframe=
+ data-iframe
中包含的任何内容。
现在你只需要处理索引上的传入请求.html如下所示。
.HTML
<iframe id="iframe"></iframe>
.JS
$(function () {
if (typeof getUrlVars()["iframe"] != 'undefined') {
$("#iframe").attr("src", getUrlVars()["iframe"]);
}
});
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
从这里借来的getUrlVars。
试试这个:
<td onclick="(function(){window.location='index.html';})()" style='cursor: hand; cursor: pointer;' background="images/static.gif" id="td1" width="25%" bgcolor="#FFFFFF">
但是Martijn是对的,如果可能的话,你不应该在你的标签中内联任何Javascript或CSS