[英]How to click on a link and call function on the page that link go to as the same time?
category1
, category2
, category3
changeIframe([category1 | category2 | category3]);
当我点击“index.html”页面上的菜单时,链接会将我带到“product.html”页面,然后立即调用函数changeIframe(var)
。 该changeIframe(var)
函数将比较$var
(价值var
其次是菜单,我点击的名称),然后更改此页的内容。 我怎么能这样做?
只是一个想法,将类别作为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。 如果使用服务器端脚本会更容易。
在链接上添加类别作为主题标签并阅读。
<a href="product.html#category1">menu link</a>
在您的产品页面中
window.onload = function(){
var category = (window.location.hash).replace("#",'');;
alert(category);
// changeIframe(category)
}
并删除像@Charlie节目一样的“#”。
的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>
在index.phtml页面上,当您单击链接传递菜单名称作为查询字符串时,当您到达product.phtml时,调用$(document).ready函数上的changeiframe(var)
使用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'] ?>)
传递链接作为查询字符串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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.