如何点击链接上的链接和呼叫功能同时进行链接?

时间:2013-04-10 04:52:06

标签: javascript html function

  • index.html - 包含菜单category1category2category3
  • product.html - 具有功能changeIframe([category1 | category2 | category3]);

当我点击“index.html”页面上的菜单时,链接会将我带到“product.html”页面,然后立即调用函数changeIframe(var)changeIframe(var)函数将比较$varvar的值后跟我点击的菜单名称),然后更改此页面中的内容。我怎么能这样做?

6 个答案:

答案 0 :(得分:2)

只是一个想法,将该类别作为Url Hash传递。

的index.html:

<a href="product.html#category1">Category 1</a>
<a href="product.html#category2">Category 2</a>
<a href="product.html#category3">Category 3</a>

product.html

var category = (location.hash).replace('#','');
changeIframe(category); //call function

如果只有你需要使用javascript。如果使用服务器端脚本,它会更容易。

答案 1 :(得分:1)

在链接上添加类别作为主题标签,并将其读出来。

<a href="product.html#category1">menu link</a>

在您的商品页面

window.onload = function(){

    var category = (window.location.hash).replace("#",'');;
    alert(category);
    // changeIframe(category)

}

删除像@Charlie节目一样的“#”。

答案 2 :(得分:1)

的index.html

<a href="product.html#category1">category 1</a>
<a href="product.html#category2">category 2</a>
<a href="product.html#category3">category 3</a>

product.html

$(document).ready(function(){
    var item =  toLowerCase((document.location.hash)).replace('#','');
    if(/category[1-3]/i.test(item)){
        changeIframe(item);
    }else{
        changeIframe(defaultitem);
    }
});

如果您使用的是php

的index.html

<a href="product.html?item=category1">category 1</a>
<a href="product.html?item=category2">category 2</a>
<a href="product.html?item=category3">category 3</a>

product.html

<script>
<?php
if(isset($_GET['item']) && preg_match("/category[1-3]/", $_GET['item'])){
    echo "changeIframe(" . $_GET['item'] .");";
}else{
    echo "changeIframe(defaultitem);";
}
</script>

答案 3 :(得分:0)

在index.phtml页面上,当您单击链接传递菜单名称作为查询字符串时,当您到达product.phtml时,调用$(document).ready function上的changeiframe(var)

答案 4 :(得分:0)

使用PHP进行此操作的一种方法(如果您有支持它的服务器)。

如果你最终得到PHP设置,这里有一个选项:

的index.php:

<a href="product.php?cat=1">Category 1</a>
<a href="product.php?cat=1">Category 2</a>
<a href="product.php?cat=1">Category 3</a>

然后将此代码与product.php中的Javascript一起使用以获取传递的类别:

changeIframe(<?php $_GET['cat'] ?>)

答案 5 :(得分:0)

将链接作为查询字符串product.html?category=1传递,并可在该页面中使用此代码

  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;

    }



    $(document).ready(function() {   

   var id = getUrlVars()["category"];
    changeIframe(var);
    });
相关问题