Hiển thị các bài đăng có nhãn JS. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn JS. Hiển thị tất cả bài đăng

Thứ Hai

Highlight Keywords Làm nổi bật từ khóa với javascript

Trong bài viết về Highlighting Keywords lần trước tôi có minh họa cách đánh dấu từ khóa tìm kiếm với asp.net C#. Nhưng đó là code C#- Xử lý phía Server. Trong bài viết này tôi sẽ tiếp tục chủ đề này với cải tiến hơn đó là thực hiện tại máy client - sử dụng javascript. DEMO
Thông thường khi bạn viết form tìm kiếm bạn đưa từ khóa tìm kiếm lên các parameter của url. Dựa vào đây ta sẽ đánh dấu từ khóa người dùng đang tìm kiếm.
Bước 1: Tạo Style sheet highlight:
<style type="text/css">
 .highlight{
  color:#f00;
  background-color:#ff0;
  font-weight:bold;
 }
 </style>
Bước 2: Viết code javascript phân tích và thêm style sheet cho từ khóa tìm kiếm: 
<script type="text/javascript">
var kw = [];
var qsParm = []; 
function qs() 
{
 var query = window.location.search.substring(1); 
 var parms = query.split('&'); 
 for (var i=0; i<parms.length; i++) 
 {
  var pos = parms[i].indexOf('='); 
  if (pos > 0) 
  {
   var key = parms[i].substring(0,pos); 
   var val = parms[i].substring(pos+1); 
   qsParm[key] = val;
  }
 }
} 
qsParm['keyword'] = null; qs();
if (qsParm['keyword'] != null) kw = qsParm['keyword'].split(',');

function start() 
{
 var bdy = document.getElementsByTagName('body')[0].innerHTML; 
 for (var i = kw.length - 1; i >= 0; i--) 
 {
  var re = new RegExp('(\\b'+kw[i]+'\\b)','ig'); 
  bdy = bdy.replace(re,'<span class="highlight ">$1<\/span>'); 
  var re1 = new RegExp('(<[^>]*?)<span class="highlight">('+kw[i]+')<\/span>(.*?>)','ig'); 
  bdy = bdy.replace(re1,'$1$2$3');
  var re2 = new RegExp('(<script.*?>)<span class="highlight">('+kw[i]+')<\/span>(<\/script>)','ig'); 
  bdy = bdy.replace(re2,'$1$2$3'); 
  var re3 = new RegExp('(<textarea.*?>)<span class="highlight">('+kw[i]+')<\/span>(<\/textarea>)','ig'); 
  bdy = bdy.replace(re3,'$1$2$3');
 } document.getElementsByTagName('body')[0].innerHTML = bdy;
}
window.onload = start;
</script>
Với code javascript trên sẽ tìm các từ khóa (Nếu nhiều từ khóa bạn để phân cách bẳng dấu , ). Và thay thế bằng các thẻ span có class là highlight với các từ khóa này bên trong thẻ Body của trang.
Anh Khoa

Chủ Nhật

JavaScript - Tự động chuyển trang– Auto Redirect cho website

4u4m- JavaScript iải quyết việc tự động chuyển trang (Auto Redirect) đang xem tới 1 địa chỉ (URL) mà ứng dụng bạn muốn chuyển tới. Case Study ở đây là website của bạn bằng cách nào đó xử lý xong xuôi tại trang A và bây giờ bạn muốn tự động chuyển tới 1 trang B nào đó. Trang B có thể là 1 webpage của website của bạn hoặc một website khác.
Để giải quyết được vấn đề này hiện tại có 3 hướng giải quyết chính:
1.Sử dụng HTTP Status Code 301 (hoặc 302)
2.Sử dụng thẻ META của HTML
3.Sử dụng cơ chế Timeout của Javascript.


Mình sẽ lần lượt giới thiệu 3 cách triển khai cũng như ưu thế, bất lợi của từng giải pháp.
1.Sử dụng HTTP Status Code 301 (hoặc 302) 
Cách này dựa trên cơ chế của HTTP, nếu trình duyệt nhận được 1 HTTP Response mà HTTP Header có Status code là 301 hoặc 302 và kèm theo “Location: some_url” thì trình duyệt sẽ tự động chuyển đến trang mà bạn chỉ định trong location.

Để làm được thao tác gởi Header theo ý mình thì tùy vào từng ngôn ngữ lập trình mà nó sẽ cung cấp cho bạn các cơ chế khác nhau để gởi header nhưng chung quy lại thì công việc cuối cùng là tạo 1 cái HTTP Response có Status code là 301 (hoặc 302).
Tại sao lại là 301 hoặc 302?
Đối với các ngôn ngữ khác thì mình chưa kiểm chứng, nhưng đối với PHP, nếu chỉ sử dụng PHP cú pháp gởi header bằng cách dùng header(“location: some_url”) thì chỉ tạo được header có status code là 302(Found) chứ không phải 301(Moved Permanently), do đó muốn nhận được status code 301 ở phía trình duyệt thì bạn cần phải gởi thêm status code trước khi gởi location. Mình nghĩ các ngôn ngữ lập trình khác cũng tương tự nhỉ ^^!
Dưới đây là danh sách cách triển khai sử dụng Header của 1 số ngôn ngữ lập trình mà mình sưu tầm được.
--------------------------------------------------------------------- PHP Redirect 
<?
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://www.new-url.com" );
?>
----------------------------------------------------------------------

ColdFusion Redirect 
<.cfheader statuscode="301" statustext="Moved permanently">

<.cfheader name="Location" value="http://www.new-url.com">
-----------------------------------------------------------------------

ASP Redirect 
<%@ Language=VBScript %>

<%

Response.Status="301 Moved Permanently"

Response.AddHeader "Location","http://www.new-url.com/"

%>

---------------------------------------------------------------------- ASP .NET Redirect 
<script runat="server">

private void Page_Load(object sender, System.EventArgs e)

{

Response.Status = "301 Moved Permanently";

Response.AddHeader("Location","http://www.new-url.com");

}

</script>

----------------------------------------------------------------------- JSP (Java) Redirect 
<%

response.setStatus(301);

response.setHeader( "Location", "http://www.new-url.com/" );

response.setHeader( "Connection", "close" );

%>
----------------------------------------------------------------------
CGI PERL Redirect 
$q = new CGI;

print $q->redirect("http://www.new-url.com/");
----------------------------------------------------------------------
Ruby on Rails Redirect 
def old_action
headers["Status"] = "301 Moved Permanently"
redirect_to "http://www.new-url.com/"
end
----------------------------------------------------------------------

Đối với cách sử dụng Header thì sẽ có 1 cái bất lợi đó là trong trường hợp bạn muốn xuất một nội dung gì đó ra rồi chuyển trang sẽ không thành công, bởi vì do cơ chế của HTTP, sau khi trình duyệt nhận được Header status code 301 (hoặc 302) và có location kèm theo thì nó sẽ tự động chuyển và bỏ qua các nội dung mà bạn xuất. Riêng đối với PHP, trước hàm header() mà bạn xuất dù chỉ 1 ký tự thì script sẽ báo lỗi và hàm header() sẽ không được thực hiện, do đó sẽ không xảy ra quá trình tự động chuyển trang. Còn các ngôn ngữ khác thì không biết giải quyết được vụ báo lỗi không ^^.
Vì giới hạn của cách thức này, nếu bạn muốn xuất một nội dung gì ra trong vòng vài giây rồi mới tự động chuyển thì chỉ có cách sử dụng 2 cách còn lại là sử dụng thẻ META của HTML hoặc sử dụng Javascript.
2.Sử dụng thẻ META của HTML 
Cách này dùng rất đơn giản và tiện lợi, hiệu quả thì cực kỳ tốt. Bạn có thể cho phép trang A hiển thị bao lâu đó rồi sau đó sẽ tự động chuyển sang trang B.Chỉ cần thêm thẻ META dưới đây vào phần HEAD của trang HTML thì sẽ đạt được hiệu quả.


[sup]http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples[/sup]
http://bloghoctap.com/wp-content/plugin ... _meta.html

MÃ: CHỌN TẤT CẢ
<html>
<head>
<meta http-equiv="refresh" content="15;url=http://www.new-url.com/">
</head>
<body>
...
</body>
</html>


Trong ví dụ này, website sẽ hiển thị 15 giây, sau đó sẽ chuyển tới trang http://www.new-url.com/. Bạn có thể thay đổi thời gian và URl bằng cách thay đổi 2 tham số trong content=”…”.
Giải pháp này được áp dụng phổ biến bởi tính Usability của nó, tuy nhiên trong 1 số trường hợp bạn không thể sử dụng thẻ META thì chỉ có cách sử dụng Javasript thông qua hàm setTimeout().
3.Sử dụng cơ chế Timeout của Javascript 
Khi nghĩ tới Javascript có lẽ là lựa chọn cuối cùng của bạn rồi bởi vì dùng nó sẽ bị tốn “một xíu” tài nguyên trình duyệt và làm cho webpage chậm “một xíu”. Tuy nhiên, nếu bất khả kháng thì phải dùng thôi.
Dưới đây là 1 ví dụ đơn giản về sử dụng cơ chế Timeout để chuyển trang, hiệu quả sẽ tương tự như ví dụ ở phần sử dụng thẻ META

[sup]http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples[/sup]
http://bloghoctap.com/wp-content/plugin ... ct_js.html


MÃ: CHỌN TẤT CẢ
<html>
<head>
<script type="text/javascript">
<!--
function delayer(){
window.location = "http://www.new-url.com/"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()', 15000)">
<h2>Prepare to be redirected after 15 second(s)!</h2>
</body>
</html>


Tuy nhiên, khi nghĩ tới Javascript là ta có thể triển khai nhiều điều thú vị cho việc redirect, ví dụ như ngoài việc hiển thị thời gian chuyển trang, bạn có thể cho số thời gian đếm ngược(mỗi lần trừ 1 giây và hiển thị số thời gian còn lại ra), như vị ứng dụng chuyển trang trong có vẻ ấn tượng hơn. Dưới đây là đoạn Javascript cũng làm công việc như ví dụ trên, nhưng kỳ này thời gian sẽ đếm ngược và hiển thị ra màn hình.


[sup]http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples[/sup]
http://bloghoctap.com/wp-content/plugin ... tdown.html

MÃ: CHỌN TẤT CẢ
<html>
<head>
<script type="text/javascript">
var time = 15; //How long (in seconds) to countdown
var page = "http://www.new-url.com/"; //The page to redirect to
function countDown(){
time--;
gett("container").innerHTML = time;
if(time == -1){
window.location = page;
}
}
function gett(id){
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init(){
if(gett('container')){
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else{
setTimeout(init, 50);
}
}
document.onload = init();
</SCRIPT>
</head>
<body>
<h2>Prepare to be redirected after <span id="container"></span> second(s)!</h2>
</body>
</html>


—————————————————
Tóm lại, dù cách nào đi nữa thì các bạn (những Developer) cũng hãy luôn nghĩ tới giải pháp nào tốt nhất và phục vụ tốt nhất cho user của mình. Hy vọng bài viết này sẽ giúp các bạn phần nào trên con đường “làm web” của mình ^^.
----------- Sưu tầm------------

Thứ Bảy

Javascript Alert Box

A javascript alert box is a dialog box that pops-up with a message and an 'OK' button. The alert method displays an alert box with a string passed to it. For example: alert() will display an empty dialog box with just the 'OK' button. alert("Hello world") will display a dialog box with the message, 'Hello world' and an 'OK' button. (it remains paused until it is clicked). You can display any type of value on an alert box.
For example:
var number = 12345
alert("The number is: "+number)
This simply displays, 'The number is: 12345' on an alert box. The '+' sign ties the two values that are to be displayed in one statement. 
 
Here is a javascript alert box that pops-up when the page is loaded: 
 

<html>
<body>
<script type="text/javascript">
alert("Hello world")
</script>
</body>
</html>
Hello world is displayed in a dialog box when the page is loaded.

 
Here is a javascript alert box that pops-up when a link is clicked: 
 
<html>
<body>
<A HREF='javascript:onClick=alert("Not an active link")'>Click here</A>
</body>
</html>
onClick is an event that understands the mouse click. We set the onClick event to the alert box so that when the active link is clicked, the onClick event executes the alert box.
Here is the result of this example:
asdhfasd

 
Here is a javascript alert box that pops-up when a button is clicked: 
 
<html>
<body>
<form>
<input type="button" name="click" value="Click To Alert" onclick='alert("You clicked a button to display an alert box")'>
</form>
</body>
</html>
Again, we used the onClick event to display the alert box when the button is clicked.
Here is the result of this example:

 

Javascript Prompt Box

The prompt() is a method of the window object, just like alert() we just saw. The format for prompt() is similar to alert(), except for one addition. Prompt uses a text field to enter a value. It also has 'OK' and 'CANCEL' buttons, while the alert has only one button.
Here is an example of a prompt box:
prompt("Type your name:"). This prompt method will display the message, 'Type your name' on a prompt box and text field with the default text of undefined. We can display default text in the text field by simply doing the following:
prompt("Type your name:", "Type here")
The information submitted to the prompt() can be stored in a variable as follows:
var name = prompt("Type your name:", "Type here")
Once we have a value from the prompt box stored in a variable, we can display it on a message box. 
 
Here is a javascript prompt box that displays the provided value on a message box: 
 
<html>
<body>
<script type="text/javascript">
var name = prompt("What is your name?", "Type your name here");
alert("Your name is: "+name)
</script>
</body>
</html>
This example displays a prompt box when the page is loaded with the message, 'What is your name?' and the default text field value of, 'Type your name here'. Once a name is provided, it is stored in the variable name, and is displayed on an alert box.

Javascript Confirm Box

The Javascript confirm box differs from a regular alert box in that it provides two choices for the user: 'OK' and 'CANCEL' to confirm the request. You can use a variable and an if statement to determine if the 'OK' or 'CANCEL' button is clicked.
Here is an example of a confirm box:
Confirm: ("Do you want to continue?") This displays a dialog box with the message, 'Do you want to continue?' (with 'OK' and 'CANCEL').

 
Here is a javascript confirm box that tells you which button you clicked:

 
<html>
<body>
<script type="text/javascript">
var answer = Confirm: ("Do you want continue?")
if (answer)
alert("You said: Ok")
else
alert("You said: Cancel")
</script>
</body>
</html>
We stored the confirm objects in the variable, answer, and then used an if statement to determine which button was clicked. The default and expected button is, 'Ok' so we stated if the answer is equal to 'Ok', then go to a specify location. Else will be "true", and the second message will be displayed, if the current value of answer is not the default value.

 
Here is an example that directs the user to another page when the, 'OK' button is clicked: 
 
<html>
<body>
<script type="text/javascript">
var answer = Confirm: ("Do you want a different page?")
if (answer)
window.location = "http://www.videogamedeals.com"
else
alert("Nothing happened")
</script>
</body>
</html>
We stored the confirm objects in the variable answer, and then used an if statement to determine which button was clicked. The default and expected button is, 'Ok' so we stated that if the answer is equal to 'Ok', then go to: www.videogamedeals.com. Else will be "true", and the second message, 'Nothing happened' will be displayed if the current value of answer is not the default value.

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Blogger Templates