详解前端在详解前端在html页面之间传递参数的方法页面之间传递参数的方法
主要介绍了详解前端在html页面之间传递参数的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参
考。一起跟随小编过来看看吧
项目中经常会出现的一种情况,有一个列表,譬如是案例列表,点击列表中的某一项,跳转至详情页面。详情是根据所点击的
某条记录生成的,因为案例和具体的详情页面,都是用户后期自行添加的,我们开始编写时,不可能穷尽。因此跳转页面时,
我们需要传递一个参数过去,这样我们才能通过这个参数进行数据请求,然后根据后台返回的数据来生成页面。因此,通过a
标签跳转的方式,肯定是行不通的。
我们经常写form表单,提交时,可以传递参数,如果使用表单,并将其隐藏起来,应该可以达到效果。
除此以外,window.location.href和window.open也可以达到效果。
1、通过、通过form表单传递参数表单传递参数
<html lang="en">
<head>
<!--网站编码格式,UTF-8 国际编码,GBK或 gb2312 中文编码-->
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="Keywords" content="关键词一,关键词二">
<meta name="Description" content="网站描述内容">
<meta name="Author" content="Yvette Lau">
<title>Document</title>
<!--css js 文件的引入-->
<!-- <link rel="shortcut icon" href="images/favicon.ico"> -->
<link rel="stylesheet" href=""/>
<script type = "text/javascript" src = "jquery-1.11.2.min.js"></script>
</head>
<body>
<form name = "frm" method = "get" action = "receive.html" onsubmit = "return foo()" style = "position:relative;">
<input type="hidden" name="hid" value = "" index = "lemon">
<img class = "more" src = "main_jpg10.png" />
<input type = "submit" style = "position:absolute;left:10px;top:0px;width:120px;height:40px;opacity:0;cursor:pointer;"/>
</form>
<form name = "frm" method = "get" action = "receive.html" onsubmit = "return foo()" style = "position:relative;">
<input type="hidden" name="hid" value = "" index = "aaa">
<img class = "more" src = "main_jpg10.png" />
<input type = "submit" style = "position:absolute;left:10px;top:0px;width:120px;height:40px;opacity:0;cursor:pointer;"/>
</form>
<form name = "frm" method = "get" action = "receive.html" onsubmit = "return foo()" style = "position:relative;">
<input type="hidden" name="hid" value = "" index = "bbb">
<img class = "more" src = "main_jpg10.png" />
<input type = "submit" style = "position:absolute;left:10px;top:0px;width:120px;height:40px;opacity:0;cursor:pointer;"/>
</form>
</body>
</html>
<script>
function foo(){
var frm = window.event.srcElement;
frm.hid.value = $(frm.hid).attr("index");
return true;
}
</script>
点击图片时,跳转至receive.html页面。页面的url变成:
我们想要传的字符串已经传递了过来。
然后再对当前的url进行字符串分割
window.location.href.split(“=”)[1]//得到lemon
我们拿到需要传来的参数之后,就可以根据这个进行下一步的处理了。
除了上述通过字符串分割来获取url传递的参数外,我们还可以通过正则匹配和window.location.search方法来获取。
2、通过、通过window.location.href
譬如我们点击某个列表,需要传递一个字符串到detail.html页面,然后detail.html页面根据传来的值,通过ajax交互数据,加载
页面的内容。
var index = "lemon"; var url = "receive.html?index="+index; $("#more").click(function(){ window.location.href = url; });
评论0