ตัวอย่างโค้ดต่อไปนี้ เป็นแนวทางในการใช้งาน cookie สำหรับกำหนด การเปลี่ยนพื้นหลังด้วยรูปภาพที่ต้องการ ให้เก็บเว็บเพจ สามารถนำไปประยุกต์ใช้กับการเปลี่ยน theme หรือ style sheet
วิธีสร้างไฟล์ทดสอบ เพื่อทำความเข้าใจ
1.สร้างไฟล์ page1.php ตามโค้ดด้านล่าง
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>background 1</title>
</head>
<body>
<a href="page2.php">page 2</a>
<br />
<a href="#" class="setbg" rel="https://www.ninenik.com/images/8.jpg">background 1</a><br />
<a href="#" class="setbg" rel="https://www.ninenik.com/images/9.jpg">background 2</a>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
$(document.body).css("background","url(<?=$_COOKIE['bgSet']?>)");
$(".setbg").click(function(){
var days=10; // กำหนดจำนวนวันที่ต้องการให้จำค่า
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = "bgSet=" +$(this).attr("rel")+ "; expires=" + expires + "; path=/";
$(document.body).css("background","url("+$(this).attr("rel")+")");
});
});
</script>
</body>
</html>
2.สร้างไฟล์ page2.php ตามโค้ดด้านล่าง
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>background 2</title>
</head>
<body>
<a href="page1.php">page 1</a><br />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
$(document.body).css("background","url(<?=$_COOKIE['bgSet']?>)");
});
</script>
</body>
</html>
3.ทดสอบการใช้งาน
จากผลลัพธ์ตัวอย่างเป็นการ เรียกใช้งาานการกำหนด background ด้วย javascript .ใน jQuery
เราสามารถกำหนดการใช้งานได้โดยตรงเช่น
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>background 1</title> </head> <body background="<?=$_COOKIE['bgSet']?>"> ...... ... ..