12 พฤศจิกายน 2553

การแทรก jQuery ง่ายๆ เพื่อแก้ไข Links ภายใน Blogspot

เราจะใช้เมื่อไม่ต้องการให้ Links ภายใน Blogspot กดแล้วเรียก Webpage ใหม่มาแทนหน้าเดิมที่เราใช้อยู่ในปัจจุบัน แต่ต้องการให้เปิดหน้าใหม่ขึ้นมาแทน โดยแบ่งเป็นกรณีต่างๆ ดังนี้

กรณีต่างๆ Code ที่ใช้ คือ
กรณีที่ 1 - เมื่อต้องการให้ทุกๆ Links เปิดหน้าใหม่ทุกครั้ง<script src='http://code.jquery.com/jquery-1.4.3.min.js' type='text/javascript'/>

<script language='javascript'>
$(document).ready(function () {
$('a').attr({ 'target': '_blank' });
});
</script>
กรณีที่ 2 - เมื่อต้องการให้เฉพาะ Links ที่เปิด Website อื่นๆ ภายนอก เท่านั้นที่ Blogspot เปิดหน้าใหม่<script src='http://code.jquery.com/jquery-1.4.3.min.js' type='text/javascript'/>

<script language='javascript'>
$(document).ready(function () {
$('a').attr({ 'target': '_blank' });
$('a[href *= blogger.com] , a[href *= blogspot.com]').attr({ 'target': '_self' });
});
</script>


โดยเราจะทำการแทรก Code นี้ระหว่าง tag header (หมายถึงระหว่าง <head></head>) ดังนี้

Code เดิม<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
// แทรก Code ลงตรงนี้
<b:include data='blog' name='all-head-content'/>
<title><data:blog.pageTitle/></title>
Code เมื่อแทรก jQuery ลงไปแล้ว<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
// แทรก Code ลงตรงนี้
<script src='http://code.jquery.com/jquery-1.4.3.min.js' type='text/javascript'/>

<script language='javascript'>
$(document).ready(function () {
$('a').attr({ 'target': '_blank' });

$('a[href *= blogger.com] , a[href *= blogspot.com]').attr({
'target': '_self'
});
});
</script>

<b:include data='blog' name='all-head-content'/>
<title><data:blog.pageTitle/></title>


ข้อเสนอแนะ

1. เท่านี้ Links ทั้งหมดใน Blogspot ของคุณก็จะทำงานโดยเปิดหน้า Webpage ใหม่แทน ตามที่คุณต้องการ แต่หากไม่ทำงานตามที่ระบุไว้ก็เป็นไปได้ว่าอาจมีการเรียก Javascript อื่นใน Page ที่อาจทำให้คำสั่งบางอย่างของ jQuery ทำงานผิดพลาดได้ แต่การแก้ไขอาจยุ่งยากขึ้นอีกเล็กน้อยครับ

2. ไม่สามารถทำงานได้ใน Blog ที่ไม่มีการให้เข้าไปแก้ Html หรือ Blog การทำงานบางอย่างของ Javascript

Credit : www.jQuery.com

ไม่มีความคิดเห็น:

แสดงความคิดเห็น