JavaScript筆記之用鏈接對用戶進行重定向

       可以根據用戶是否打開了JavaScript功能,無縫地對用戶進行重定向(redirection),也就是將用戶轉到另一個頁面。這個示例演示如何將重定向功能嵌入鏈接中,下面將使用兩個HTML頁面和一個JavaScript文件。

       第一個HTML頁面向用戶顯示連接:

test.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>	
<title>Welcome to our site</title>
	<script type="text/javascript" src="script01.js">
</script>
</head>
<body bgcolor="#FFFFFF">
	<h2 align="center">
	<a href="script01.html" id="redirect">Welcome to our site... c'mon in!</a>
	</h2>
</body>
</html>

第二個HTML頁面是在用戶啓用了JavaScript功能情況下用戶被重定向到得HTML頁面。

jswelcome.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Our site</title>
</head>
<body bgcolor="#FFFFFF">
	<h1>Welcome to our web site, which features lots of cutting-edge JavaScript</h1>
</body>
</html>

script01.js

window.onload = initAll;

function initAll() {
	document.getElementById("redirect").onclick = initRedirect;
}

function initRedirect() {
	window.location = "jswelcome.html";
	return false;
}



 

script01.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>My JavaScript page</title>
</head>
<body bgcolor="#FFFFFF">
<noscript>
	<h2>This page requires JavaScript.</h2>
</noscript>
</body>
</html>

當用戶打開"test.html"時,根據他們是否打開了javascript功能,將被帶到script01.html或jswelcome.html兩個頁面之一。

js文件中的

function initRedirect() {
	window.location = "jswelcome.html";
	return false;
}

如果調用這個函數,它就將window.location(即瀏覽器中顯示的頁面)設置爲一個新的頁面。return false表示停止對用戶點擊的處理,這樣就不會加載href頁面中指定的頁面,這種方式最酷的特色是,完成了重定向而用戶根本不會意識到頁面發生了重定向。(源《JavaScript基礎教程》)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章