Javascript检查页面网址,然后加载相应的iframe

Javascript to check page url, and then load corresponding iframe?

本文关键字:加载 iframe 然后 检查 Javascript      更新时间:2023-09-26

我可以得到一些关于我遇到的问题的指示吗?

短版本

有谁知道我是否可以根据父页面的名称使用 javascript 加载特定的 iframe:

如果页面名称 ="http://www.example.com/products/pens",则 iframe 内容 = 笔.htm

如果页面名称 ="http://www.example.com/products/electronics",则 iframe 内容 = 电子产品.htm

更多信息

我需要改进电子商务商店的导航,这是一个现成的设置,您只能使用 css 和一些 javascript 来品牌和重新设计商店,或者插入 HTML 块。大约有 14 个父类别,每个类别中大约有 10 个子类别。

我想在类别页面模板中添加一个自动高度的 iframe html 块,并使用它来显示子类别和图像的列表。

是否有一些 javascript 可以用来检测类别页面名称,然后加载相应的 iframe?

我想使用一个 HTML 块,并根据父页面名称加载十个 iframe。

任何帮助都非常感谢

戴夫

您可以将 iframe 指向初始的"选择器"页面...然后在那里,检查父母的位置,然后进行重定向。

例如:

这将在类别页面中。

<iframe src="Picker.htm"></iframe>

这将是"拾取器.htm的内容

<script type="text/javascript">
switch (parent.location.href.toLowerCase())
{
    case "http://www.example.com/products/pens":
        location.href = "pens.htm";
        break;
    case "http://www.example.com/products/electronics":
        location.href = "electronics.htm";
        break;
}
</script>

检查路径名中是否有"笔"或"电子",并相应地更改 iframe 源:

if (window.location.pathname.match('pens')) {
    $('iframe').attr('src', 'pens.htm');
    // document.getElementById('id').src = 'pens.htm'; // 'id' = id of iframe
    // or, if iframe has no id, use document.getElementsByTagName('iframe'), etc.
} else if (window.location.pathname.match('electronics')) {
    $('iframe').attr('src', 'electronics.htm');
    // document.getElementById('id').src = 'electronics.htm';
}

编辑:由于允许jQuery,我已经注释掉了native-JS答案并使用jQuery

您可以检查主document.location并相应地设置iframesrc属性。 这就是你要找的吗?

if (window.location.href.toLowerCase().indexOf('/products/pens') > 0){
$('#iframeid').attr('src', '/pens.html');
} else if (window.location.href.toLowerCase().indexOf('/products/electronics') > 0){
$('#iframeid').attr('src', '/electronics.html');
}

或者,如果页面上不存在 iframe,您可以通过 jQuery 添加它:

if (window.location.href.toLowerCase().indexOf('/products/pens') > 0){
   $('.iframePlaceHolder').append('<iframe src="pens.htm" />');
} else if (window.location.href.toLowerCase().indexOf('/products/electronics') > 0){
   $('.iframePlaceHolder').append('<iframe src="electronics.htm" />');
}

如果您没有使用 JQuery,则可以执行以下操作来添加 iframe:

var newIframe = document.createElement('iframe');
if (window.location.href.toLowerCase().indexOf('/products/pens') > 0){
    newIframe.src = "pens.htm";
} else if (window.location.href.toLowerCase().indexOf('/products/electronics') > 0){
    newIframe.src = "electronics.htm";
}
document.getElementById('idOfPlaceHolder').appendChild(newIframe);