Danh mục

Thứ Bảy, 16 tháng 10, 2010

jQuery - ajax

jQuery ajax giúp chúng ta đơn giản hóa quá trình thực thi. Sau đây là một vài minh họa về tính tiện dụng của JQuery ajax.

Cú pháp

jQuery.ajax({
type:"POST", //Phương thức gửi request là POST hoặc GET
data:"id=12&name=abc", //tham số gửi kèm
dataType:"xml", //kiểu dữ liệu trả về, mặc định là text
url:"/login/servletLogin", //Đường dẫn tới nơi xử lý request ajax
success: function (){ //hàm gọi về khi thực hiện thành công
// mã lệnh
}
});

Ví dụ 1: Sử dụng HTML tạo một ví dụ đơn giản với jQuery ajax

  • Tạo một thư mục(ở đây tạm gọi là thư mục VD).
  • Vào thư mục VD tạo một file index.html có nội dung như sau
  • <html>
    <head>
     <script src="http://code.jquery.com/jquery-1.4.2.js"></script>
     <script type="text/javascript">
      jQuery(document).ready(function(){
       jQuery("#ajaxButton").click(function(){
        jQuery.ajax({
         type:"POST",
         url:"ajax.html",
         success:function(html){
          jQuery("#responseDiv").html(html);
         }
        });
       });
      });
     </script>
    </head>
    <body>
     <div>
      <input type="button" value="ajax" id="ajaxButton"/>
     </div>
     <div id="responseDiv">
     
     </div>
    </body>
    </html>

  • Tiếp tục tạo file ajax.html có nội dung như sau
  • <style>
    #sampleTable{
     border-collapse:collapse;
    }
    #sampleTable td{
     border: 1px solid black;
     width:100px;
    }
    </style>
    <table id="sampleTable">
     <tr>
      <td>Name</td>
      <td>Year</td>
     </tr>
     <tr>
      <td>Van A</td>
      <td>1982</td>
     </tr>
    </table>

  • Mở file index.html bằng trình duyệt bất kỳ click vào button ajax bạn sẽ thấy toàn bộ nội dung của file ajax.html được lấy về trang index.html.

Ví dụ 2: Dùng PHP tạo một ví dụ đơn giản với jQuery ajax.

  • Cài đặt ứng dụng chạy apache như Xampp hoặc Wamp. Start ứng dụng.
  • Tạo thư mục với tên là sample trong(thư mục htdocs đối với Xampp và www đối với Wamp)
  • Trong thư mục sample tạo file index.php có nội dung như sau:
  • <html>
    <head>
     <script src="http://code.jquery.com/jquery-1.4.2.js"></script>
     <script type="text/javascript">
      jQuery(document).ready(function(){
       jQuery("#ajaxButton").click(function(){
        jQuery.ajax({
         type:"POST",
         url:"ajax.php", //goi toi file ajax.php
         data:"name="+jQuery("#name").val()+"&year="+jQuery("#year").val(),//du lieu gui di
         success:function(html){
          jQuery("#responseDiv").html(html);
         }
        });
       });
      });
     </script>
    </head>
    <body>
     <table>
      <tr>
       <td>Name:</td>
       <td><input type="text" id="name"/></td>
      </tr>
      <tr>
       <td>Year:</td>
       <td><input type="text" id="year"/></td>
      </tr>
     </table>
     <div>
      <input type="button" value="ajax" id="ajaxButton"/>
     </div>
     <div id="responseDiv">
     </div>
    </body>
    </html>

  • Tạo tiếp file ajax.php trong thư mục sampe với nội dung như sau
  • <?php
     $name = $_REQUEST['name'];//Lay parameter tu request
     $year = $_REQUEST['year'];//Lay parameter tu request
     
     echo "<div>".$name." sinh nam ".$year."</div>";//Noi dung tra ve
    ?>

  • Bây giờ bạn mở một trình duyệt web lên(IE hoặc firefox) lên gõ vào thanh địa chỉ như sau: localhost/sample/
  • Bạn điền vào hai field Name và Year nhấn button ajax bạn sẽ thấy câu chào giống như hình dưới.

Thứ Tư, 22 tháng 9, 2010

jQuery - empty và remove

empty và remove thường được dùng để xóa các phần tử trong jQuery. Tuy hai hàm này có cùng chung một hành động nhưng chúng có một chút khác biệt như sau:

  • empty chỉ xóa các phần tử con của phần tử đang truy xuất.
  • remove giống hàm empty nhưng bao gồm cả phần tử đang truy xuất và phần tử con.
Ví dụ ta có một thẻ ul như sau:
<ul id="test_ul">
<li>lorem isum1</li>
<li class="current">lorem isum2</li>
<li>lorem isum3</li>
<li>lorem isum4</li>
</ul>
Khi ta sử dụng:
  • jQuery("#test_ul").empty() jQuery sẽ xóa toàn bộ nội dung của thẻ ul có id là test_ul nhưng vẫn giữ lại bản thân thẻ đó.
  • <ul id="test_ul">
    </ul>
  • jQuery("#test_ul").remove() jQuery sẽ xóa toàn bộ nội dung của thẻ ul có id là test_ul và xóa luôn cả thẻ ul test_ul. Tuy nhiên hàm remove sẽ trả về đối tượng mà nó vừa remove để chúng ta có khả năng lưu trữ và khôi phục lại khi cần
Demo ta có ô vuông bên trái chứa thẻ ul như trên và ô bên phải sẽ chứa giá trị trả về của lần lượt từng câu lệnh phía trên.

  • lorem isum1
  • lorem isum2
  • lorem isum3
  • lorem isum4


Code


<style>
.fly {
float:left;
display:inline;
}
.clean{
clear:both;
}
.current{
color:red;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#butEmpty").click(function(){
var rmvObj = jQuery("#test_ul").empty();
jQuery("#showReturn").html(rmvObj);
});
jQuery("#butRemove").click(function(){
var rmvObj = jQuery("#test_ul").remove();
jQuery("#showReturn").html(rmvObj);
});
});
</script>
<div>
<div class="fly" style="width:200px;border:1px solid gray;height:120px;">
<ul id="test_ul">
<li>lorem isum1</li>
<li>lorem isum2</li>
<li>lorem isum3</li>
<li>lorem isum4</li>
</ul>
</div>
<div class="fly" style="margin:0px 5px;">
<input type="button" value="empty" id="butEmpty"/><br/>
<input type="button" value="remove" id="butRemove"/><br/>
</div>
<div class="fly" style="width:200px;border:1px solid gray;height:120px;" id="showReturn"></div>
<div class="clean"></div>
</div>

jQuery - XML

Khởi tạo XML

Để khởi tạo XML trong jQuery ta làm như sau:

var xml = $('<xml>');
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

Biến xml giờ đây được hiểu là một XML object. Ta chỉ việc append các node con vào trong object này.

Thêm node

Hàm find được dùng để tìm kiếm các thẻ trong xml. Ví dụ ta muốn tạo một danh sách employee. Ta làm như sau:

 //Đầu tiên ta tạo thẻ employees chứa các thẻ employee
xml.append("<employees></employees>");

//Tạo thẻ employee con
var employee = "";
employee += "<employee>";
employee += "<name>Tran Van A</name>";
employee += "<date>202020</date>";
employee += "<email>abc@yahoo.com</email>";
employee += "<phone>00000000</phone>";
employee += "</employee>";

// Sau đó ta tạo các thẻ employee con.
// Ta dùng hàm find để tìm thẻ employees vừa tạo
xml.find("employees").each(function(){

// Thêm thẻ employee vào thẻ employees
jQuery(this).append(employee);

});

Cập nhật thông tin node

Sau khi thực hiện các lệnh trên ta có được nội dung xml như sau:

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>Tran Van A</name>
<date>202020</date>
<email>abc@yahoo.com</email>
<phone>00000000</phone>
</employee>
</employees>

Ta cần cập nhật thông tin tên của employee thành Nguyễn Văn B. Ta làm như sau:

// Lấy ra danh sách tất cả các thẻ name trong file xml
//Cách một
xml.find("name").each(function(){
if (jQuery(this).text()=="Tran Van A"){
jQuery(this).text("Nguyen Van B");
}
});

//Cách hai
xml.find("employees").each(function(){
jQuery(this).find("employee").each(function(){
jQuery(this).find("name").each(function(){
if(jQuery(this).text()=="Tran Van A"){
jQuery(this).text("Nguyen Van B");
}
});
});
});

Xóa một node

Sau khi thực hiện lệnh cập nhật, ta có nội dung xml như sau

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>Nguyen Van B</name>
<date>202020</date>
<email>abc@yahoo.com</email>
<phone>00000000</phone>
</employee>
</employees>

Bây giờ ta sẽ xóa node name của employee có tên là Nguyen Van B ra khỏi nội dung XML(Dùng hàm remove)

xml.find("employees").each(function(){
jQuery(this).find("employee").each(function(){
jQuery(this).find("name").each(function(){
if(jQuery(this).text()=="Nguyen Van B"){
// Dùng hàm remove để xóa node
jQuery(this).remove();
}
});
});
});

Nội dung file XML cuối cùng sẽ như sau

<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<date>202020</date>
<email>abc@yahoo.com</email>
<phone>00000000</phone>
</employee>
</employees>

jQuery - contains selector

contains selector thường được dùng để tìm kiếm những HTML DOM có chứa chuỗi cần tìm(có phân biệt chữ hoa, chữ thường).

Cách thức sử dụng như sau:

  • jQuery(":contains('text')"): trả ra danh sách tất cả các object có chứa chuỗi text.
  • jQuery("div:contains('text')"): trả ra danh sách các object là thẻ div có chứa chuỗi text.

Ví dụ ta có thẻ ul có 5 thẻ con như sau

<ul id="contains_ul" style="float:left;">
<li>Lorem ipsum dolor sit amet.</li>
<li>Consectetur adipiscing elit.</li>
<li>Fusce semper sapien nec urna.</li>
<li>Curabitur vehicula, dui eu rutrum sollicitudin.</li>
<li>Feugiat convallis sed sit amet velit.</li>
</ul>

Điền từ cần tìm kiếm vào ô textbox, click button contains. Nếu chuỗi cần tìm kiếm nằm trong nội dung của 1 trong 5 dòng thì chữ ở dòng đó sẽ chuyển sang màu đỏ.

Code

<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#contains").click(function(){
jQuery("#contains_ul li").each(function(){
jQuery(this).css("color","black");
});
jQuery("#contains_ul li:contains('"+jQuery("#contains_text").val()+"')").css("color","red");
});
});
</script>
<div>
<ul id="contains_ul" style="float:left;">
<li>Lorem ipsum dolor sit amet.</li>
<li>Consectetur adipiscing elit.</li>
<li>Fusce semper sapien nec urna.</li>
<li>Curabitur vehicula, dui eu rutrum sollicitudin.</li>
<li>Feugiat convallis sed sit amet velit.</li>
</ul>
<div style="float:left;padding:20px 20px;">
<input type="text" value="" id="contains_text"/><br/>
<input type="button" value="contains" id="contains"/><br/>
</div>
<div style="clear:both;"></div>
</div>

Demo

  • Lorem ipsum dolor sit amet.
  • Consectetur adipiscing elit.
  • Fusce semper sapien nec urna.
  • Curabitur vehicula, dui eu rutrum sollicitudin.
  • Feugiat convallis sed sit amet velit.


Thứ Sáu, 3 tháng 9, 2010

jQuery - html và text

html và text là hai hàm thường được dùng để thao tác với nội dung của một jQuery object.

  • html: Lấy ra toàn bộ nội dung của đồi tượng đang truy xuất dưới dạng HTML (bao gồm cả các thẻ div, table...).
  • html(html text): Thiết lập nội dung của đối tượng đang truy xuất bằng chuỗi HTML truyền vào.
  • text: Lấy toàn bộ nội dung của các thẻ HTML con nhưng bỏ qua các thẻ đó (không lấy ra các thẻ HTML như div, table,br...).
  • text (text): thay đổi chuỗi nội dung của đối tượng(cho dù bạn truyền chuỗi HTML vào nhưng mặc định hàm này sẽ hiểu nó là text chứ không phải là mã HTML và sẽ hiển ra đúng những gì bạn truyền vào).

Ví dụ: ở đây ta có 1 thẻ div trong đó có chứa 2 thẻ p và một thẻ a(nội dung của nó là lorem text). Như sau:

<div style="float:left;border:1px color gray;background-color:#EAEAEA;width:200px;" id="content_div">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce semper sapien nec urna feugiat convallis sed sit amet velit.</p>
<p>Curabitur vehicula, dui eu rutrum sollicitudin.</p>
<a href="#">vehicula</a>
</div>
  • Nút getHTML: Lấy nội dung HTML của thẻ div(dùng hàm html)
  • Nút setHTML: dùng hàm html để set chuỗi HTML sau <b>Xin chao jQuery</b> cho thẻ div
  • Nút getText: Dùng hàm text lấy nội dung của thẻ div
  • Nút setText: Dùng hàm text thiết lập thử đoạn mã HTML sau <b>Xin chao jQuery</b> cho thẻ div
  • Nút Restore: Khôi phục lại nội dung ban đầu của thẻ div

Code

<script type="text/javascript">
jQuery(document).ready(function(){
 jQuery("#gettext").click(function(){
  alert(jQuery("#content_div").text());
 });
 jQuery("#settext").click(function(){
  jQuery("#content_div").text("<b>Xin chao jQuery</b>");
 });

 jQuery("#gethtml").click(function(){
  alert(jQuery("#content_div").html());
 });

 jQuery("#sethtml").click(function(){
  jQuery("#content_div").html("<b>Xin chao jQuery</b>");
 });

});
</script>
<div>
 <div style="float:left;border:1px color gray;background-color:#EAEAEA;width:200px;" id="content_div">
  <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce semper sapien nec urna feugiat convallis sed sit amet velit.</div>
  <p>Curabitur vehicula, dui eu rutrum sollicitudin.</p>
  <a href="#">vehicula</a>
 </div>
 <div style="float:left;padding:0px 20px;">
  <input type="button" value="getHtml" id="gethtml"/><br/>
  <input type="button" value="getText" id="gettext"/><br/>
  <input type="button" value="setHtml" id="sethtml"/><br/>
  <input type="button" value="setText" id="settext"/><br/>
 </div>
 <div style="clear:both;"></div>
</div>

Demo

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce semper sapien nec urna feugiat convallis sed sit amet velit.

Curabitur vehicula, dui eu rutrum sollicitudin.

vehicula




jQuery và hàm each

each là vòng lặp mà jQuery cung cấp sẵn cho ta, cách thức hàm each hoạt động tương tự như vòng lặp foreach trong C#.
  • each( function() ) vòng lặp chạy tuần tự từ object đầu mảng tới object cuối mảng.
  • each( function(index) ) vòng lặp chạy tuần tự từ object đầu mảng tới object cuối mảng, có kèm theo biến thứ tự (index).

Lưu ý:

  • each lả một vòng lặp foreach được viết bằng jQuery.
  • Để truy xuất đối tượng đang được hàm each truy xuất tới ta dùng từ khóa this, cách dùng như sau jQuery(this)

Cú pháp:

Ví dụ với hàm each( function() ) ta có thẻ ul có ba thẻ con li, dùng hàm each hiện alert có nội dung là nội dung của thẻ li đang được truy xuất tới.

<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#butEach1").click(function(){
jQuery("#ul_1 li").each(function(){
alert("Đang truy xuất tới phần tử có nội dung: " + jQuery(this).html());
});
});
});
</script>
<div>
<div style="float:left;border:1px color gray;background-color:#EAEAEA;padding-right:20px;">
<ul id="ul_1">
<li>Dòng 1</li>
<li>Dòng 2</li>
<li>Dòng 3</li>
</ul>
</div>
<div style="float:left;padding-left:20px;"><input type="button" value="Each" id="butEach1"/></div>
<div style="clear:both;"></div>
</div>

Demo

  • Dòng 1
  • Dòng 2
  • Dòng 3

Ví dụ với hàm each(function(index)) ta cũng có một thẻ ul với ba thẻ li con khi nhấn vào button Each thì ta dùng hàm each để gắn giá trị index vào từng thẻ ul con.

<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#butEach2").click(function(){
jQuery("#ul_2 li").each(function(index){
jQuery(this).html(jQuery(this).html()+" "+index);
});
});
});
</script>
<div>
<div style="float:left;border:1px color gray;background-color:#EAEAEA;padding-right:20px;">
<ul id="ul_2">
<li>Dòng</li>
<li>Dòng</li>
<li>Dòng</li>
</ul>
</div>
<div style="float:left;padding-left:20px;"><input type="button" value="Each" id="butEach2"/></div>
<div style="clear:both;"></div>
</div>

Demo

  • Dòng
  • Dòng
  • Dòng

Mình xin đính chính lại là each không chỉ hoạt động với mảng jQuery object mà còn có thể hoạt động với mảng thông thường trong javascript

Cách thức sử dụng:

jQuery.each(array, callback function(index, value))

Giả sử ta có mảng gồm 10 phần tử bất kỳ, ta dùng hàm each duyệt qua từng phần tử.

Code

<script type="text/javascript">
jQuery(document).ready(function(){
var arr = [1,2,3,40,1,20,3,50];
jQuery("#arr_each_1").click(function(){
jQuery.each(arr, function(index,value){
alert("STT " + index + ": Gia tri "+value);
});
});
});
</script>
<input type="button" value="contains method" id="arr_each_1"/>

Demo

Thứ Bảy, 21 tháng 8, 2010

jQuery - appendTo và prependTo

Hàm appendTo và prependTo được dùng để chèn một đối tượng HTML DOM đang truy xuất vào đối tượng HTML DOM ta chọn ở tham số của hàm. Có nghĩa là nó sẽ cắt toàn bộ đoạn HTML của đối tượng ta đang truy xuất để chèn vào đối tượng mà ta chọn ở tham số của hàm.
  • appendTo(jQuery selector): Chèn đối tượng HTML DOM đang được truy xuất vào cuối danh sách con của đối tượng được tham số selector chọn ra.
    • VD: jQuery("#a").appendTo("#b"); có nghĩa là toàn bộ nội dung thẻ có id là a sẽ được chèn vào cuối thẻ có id là b
  • prependTo(jQuery selector): Chèn đối tượng HTML DOM đang được truy xuất vào đầu danh sách con của đối tượng được tham số selector chọn ra.
    • VD: jQuery("#a").prependTo("#b"); có nghĩa là toàn bộ nội dung thẻ có id là a sẽ được chèn vào đầu thẻ có id là b
Ví dụ ta có hai thẻ ul như sau:
<ul id="input_ul">
<li>chèn 1</li>
<li>chèn 2</li>
<li>chèn 3</li>
</ul>
<ul id="choose_ul">
<li>Con 1</li>
<li>Con 2</li>
</ul>
Khi ta nhấn nút:
  • appendTo thì toàn bộ thẻ input_ul sẽ được chèn vào sau thẻ li con 2
  • prependTo thì toàn bộ thẻ input_ul sẽ được chèn vào trước thẻ li con 1

Code

<script>
jQuery(document).ready(function(){
jQuery("#butAppendTo").click(function(){
jQuery("#input_ul").appendTo("#choose_ul");
});
jQuery("#butPrependTo").click(function(){
jQuery("#input_ul").prependTo("#choose_ul");
});
});
</script>
<div>
<div style="float:left;border:1px solid gray;displày:block;width:350px;">
<ul id="input_ul">
<li>chèn 1</li>
<li>chèn 2</li>
<li>chèn 3</li>
</ul>
<ul id="choose_ul">
<li>Con 1</li>
<li>Con 2</li>
</ul>
</div>
<div style="float:left;padding:20px;">
<input type="button" id="butAppendTo" value="appendTo"/><br/>
<input type="button" id="butPrependTo" value="prependTo"/><br/>
</div>
</div>

Demo

  • chèn 1
  • chèn 2
  • chèn 3
  • Con 1
  • Con 2


Lưu ý:

  • Chỉ nên sử dụng hàm này khi biết rõ đối tượng bạn cần chèn là gì.
  • Tốt nhất nên dùng với cách select bằng id, tránh dùng hàm này với các selector trả về một mảng đối tượng như selector bằng name hoặc tag name. Ví dụ minh họa: Bạn hãy click nhiều lần vào bất kỳ button nào bạn sẽ thấy hàm sẽ không chạy chính xác với các selector trả về một mảng đối tượng
  • chèn 1
  • chèn 2
  • chèn 3
  1. Con 1
  2. Con 2
  1. Con 1
  2. Con 2




jQuery - append và prepend

append và prepend là hai hàm dùng để thao tác trên các con của một HTML DOM.
  • append(html): Chèn đoạn html text hoặc jQuery object vào cuối các thẻ con của HTML DOM đang truy xuất.
  • prepend(html): Chèn đoạn html text hoặc jQuery object vào đầu các thẻ con của HTML DOM đang truy xuất.
Ví dụ ta có một thẻ ul có 3 thẻ li như sau:
<ul>
<li>Con 1</li>
<li>Con 2</li>
<li>Con 3</li>
</ul>
Giả sử ta muốn chèn một thẻ li có nội dung là Con 0 vào trong thẻ ul đó.
  • Hàm append sẽ chèn thẻ li đó vào sau thẻ li Con 3.
  • Hàm prepend sẽ chèn thẻ li đó vào trước thẻ Con 1.
Code
Ví dụ ta có một thẻ ul có 5 thẻ li như sau:
<script>
jQuery(document).ready(function(){
jQuery("#butAppend").click(function(){
jQuery("#test_ul").append("<li>Con 0</li>");
});
jQuery("#butPrepend").click(function(){
jQuery("#test_ul").prepend("<li>Con 0</li>");
});
});
</script>
<div>
<div style="float:left;border:1px solid gray;displày:block;width:350px;">
<ul id="test_ul">
<li>con 1</li>
<li>con 2</li>
<li>con 3</li>
</ul>
</div>
<div style="float:left;padding:20px;">
<input type="button" id="butAppend" value="Append"/><br/>
<input type="button" id="butPrepend" value="Prepend"/><br/>
</div>
</div>

Demo

  • con 1
  • con 2
  • con 3


Thứ Năm, 19 tháng 8, 2010

jQuery - find và children

find và children là hai hàm được jQuery xây dựng để truy xuất tới các phần tử con của một HTML DOM được chọn
  • find(jquery selector): dùng để lấy toàn bộ các phần tử con(cấp 1, 2, 3...) của đối tượng hiện hành theo selector.
  • children(): dùng để lấy toàn bộ các phần tử con cấp 1 của đối tượng hiện hành theo selector.
  • children(jquery selector): dùng để lấy toàn bộ các phần tử con cấp 1 của đối tượng hiện hành theo selector.
Code
<script>
jQuery(document).ready(function(){
jQuery("#butChild1").click(function(){
jQuery("#test_ul").children().css("color","red");
});
jQuery("#butChild2").click(function(){
jQuery("#test_ul").children(".green").css("color","blue");
});
jQuery("#butFind1").click(function(){
jQuery("#test_ul").find("li").css("color","green");
});
jQuery("#butFind2").click(function(){
jQuery("#test_ul").find(".gray").css("color","yellow");
});
});
</script>
<style>
.red{color:red;}
.green{color:green;}
.blue{color:blue;}
.gray{color:gray;}
</style>
<div>
<div style="float:left;border:1px solid gray;displày:block;width:350px;">
<ul id="test_ul">
<div>con cấp 1 khong phai thẻ li</div>
<li>con cấp 1 thẻ li
<ul>
<li>con cấp 2 thẻ li
<ul>
<li>con cấp 3 thẻ li</li>
<li class="gray">con cấp 3 thẻ li có class là gray</li>
</ul>
</li>
<li class="gray">con cấp 2 thẻ li có class là gray</li>
<li class="gray">con cấp 2 thẻ li có class là gray</li>
</ul>
</li>
<li class="green">con cấp 1 thẻ li có class là green</li>
<li class="green">con cấp 1 thẻ li có class là green</li>
<li>con cấp 1 thẻ li</li>
</ul>
</div>
<div style="float:left;padding:20px;">
<input type="button" id="butChild1" value="Children not selector"/><br/>
<input type="button" id="butChild2" value="Children with selector"/><br/>
<input type="button" id="butFind1" value="Find li"/><br/>
<input type="button" id="butFind2" value="Find li with class"/><br/>
</div>
</div>

Demo

    con cấp 1 khong phai thẻ li
  • con cấp 1 thẻ li
    • con cấp 2 thẻ li
      • con cấp 3 thẻ li
      • con cấp 3 thẻ li có class là gray
    • con cấp 2 thẻ li có class là gray
    • con cấp 2 thẻ li có class là gray
  • con cấp 1 thẻ li có class là green
  • con cấp 1 thẻ li có class là green
  • con cấp 1 thẻ li



Thứ Tư, 11 tháng 8, 2010

jQuery - animate

Hàm animate dùng để thực hiện một số hiệu ứng đơn giản do người dùng tự định nghĩa dựa theo các css properties của đối tượng. Các cú pháp thường dùng của nó như sau:
  • animate(tập thuộc tính css, thời gian).
  • animate(tập thuộc tính css, thời gian, hàm trả về khi kết thúc).
Một số lưu ý:
  • +=-=: ví dụ ta có một thẻ div có width là 50px, khai báo trong hàmg width:"+=50px" có nghĩa là kết thúc hàm animate đối tượng sẽ có width = 100px. Tương tự với -=.
  • "slow" and "fast": đây là hai từ khóa được jQuery hỗ trợ để định nghĩa thời gian cho hiệu ứng, slow tương đương 600ms, fast tương đương 200ms.
  • "show", "hide" and "toggle": là những từ khóa được jQuery hỗ trợ dùng để thay thế giá trị của các thuộc tính css. VD:
    1. opacity:"toggle" có nghĩa là khi hàm animate được thực thi thuộc tính opacity của đối tượng sẽ có giá trị thay đổi như hàm hiệu ứng toggle.
    2. width:"hide" khi hàm animate được thực thi xong thuộc tính width của đối tượng sẽ bằng 0.
    3. width:"show" ngược lại với hide.
  • Để thao tác được trên các thuộc tính left, top, right, bottom thì bắt buộc position của đối tượng phải là absolute.
Ví dụ:
  1. Hiệu ứng move in, move out đơn giản
    Code
     <script type="text/javascript">
    jQuery(document).ready(function(){
    jQuery("#move_div").css("top",(jQuery("#border_div").position().top + 10)+"px");
    jQuery("#move_div").css("left",(jQuery("#border_div").position().left + 10)+"px");
    jQuery("#MoveOut").click(function(){
    jQuery("#move_div").animate({
    left:"+=200px",
    opacity:"hide"
    },2000);
    });
    jQuery("#MoveIn").click(function(){
    jQuery("#move_div").animate({
    left:"-=200px",
    opacity:"show"
    },2000);
    });
    });
    </script>
    <style>
    #border_div{
    display:block;
    width:580px;
    height:150px;
    background-color:#FBF9EA;border:1px solid black;
    }
    #move_div {
    position:absolute;
    width:250px;
    height:120px;
    border:1px solid gray;
    background-color:#F0F0F0;
    }
    </style>
    <input type="button" value="Move Out" id="MoveOut"/>
    <input style="margin-left:10px;" type="button" value="Move In" id="MoveIn"/>
    <div id="border_div">
    <div id="move_div">
    <div style="padding:9px;">
    <span style="color:gray;font-style:italic;">It hurts to love someone and not be loved in return, but what is the most painful is to love someone and never finding the courage to let the person know how you feel.</span>
    </div>
    </div>
    </div>

    Demo

    It hurts to love someone and not be loved in return, but what is the most painful is to love someone and never finding the courage to let the person know how you feel.

  2. Hiệu ứng zoom hình đơn giản.
    Code
    <script type="text/javascript">
    jQuery(document).ready(function(){
    jQuery("[name='hover_image']").css("top",(jQuery("#hover_div").position().top + 20)+"px");
    var left = 40;
    jQuery("[name='hover_image']").each(function(i,val){
    jQuery(this).css("left",(jQuery("#hover_div").position().left + left)+"px");
    left+=100;
    });
    jQuery("[name='hover_image']").hover(function(){//ham callback hoverIn
    jQuery(this).animate({
    width:"+=20",
    height:"+=20",
    left:"-=10",
    top:"-=10",
    opacity:"1",
    filter:"alpha(opacity=100)"
    },300);
    },function(){//ham callback hoverOut
    jQuery(this).animate({
    width:"-=20",
    height:"-=20",
    left:"+=10",
    top:"+=10",
    opacity:"0.4",
    filter:"alpha(opacity=40)"
    },300);
    });
    });
    </script>
    <style>
    #hover_div img{
    float:left;
    position:absolute;
    width:60px;
    height:60px;
    opacity:0.4;
    filter:alpha(opacity=40)
    }
    </style>
    <div id="hover_div" style="height:120px;background-color:#FBF9EA;border:1px solid black;">
    <img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
    <img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
    <img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
    </div>

    Demo


  3. Ví dụ về hàm trả về khi thực thi xong.
    Code
    <div style="display:block;width:580px;height:180px;background-color:#FBF9EA;">
    <script type="text/javascript">
    jQuery(document).ready(function(){
    jQuery("#animate_image").css("top",(jQuery("#animate_div").position().top + 5)+"px");
    jQuery("#animate_image").css("left",(jQuery("#animate_div").position().left + 5)+"px");
    jQuery("#hflip").click(function(){
    jQuery("#vflip").attr("disabled","true");
    jQuery("#hflip").attr("disabled","true");
    jQuery("#animate_image").animate({
    width:"-=130px",
    left:"+=65"
    },2000,function(){
    jQuery("#animate_image").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQon1AZE6YTMvpQhAexBVKzHKmXkhKMlQJ2uSzhfQ7ubwPr0DneArskx7p7Y5FPNa94Wjw0VW8k9R_XkmW7Y1iCmgSiJtM-D7wy0zD25TMS05L76vg1VaJ9L-mECVgoDJhz-MF3cigG4n8/s1600/hadat1.jpg").animate({
    width:"+=130px",
    left:"-=65"
    },2000,function(){
    jQuery("#animate_image").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQon1AZE6YTMvpQhAexBVKzHKmXkhKMlQJ2uSzhfQ7ubwPr0DneArskx7p7Y5FPNa94Wjw0VW8k9R_XkmW7Y1iCmgSiJtM-D7wy0zD25TMS05L76vg1VaJ9L-mECVgoDJhz-MF3cigG4n8/s1600/hadat1.jpg").animate({
    width:"-=130px",
    left:"+=65"
    },2000,function(){
    jQuery("#animate_image").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3S53eiH_TNlJT1OWhjrzjXlyll4u1ntN2KDDck0fNS1sS9b3fhKEclthS8eYA8EJK4VuTwXLgfPiFjEazLqfuEOFAmxoZRJqJ8MqNR1FLlYRMXMIchZe-eq792uEJTaDKB_bx5R8PQO7R/s320/hadat.jpg").animate({
    width:"+=130px",
    left:"-=65"
    },2000,function (){
    jQuery("#vflip").removeAttr("disabled");
    jQuery("#hflip").removeAttr("disabled");
    });
    });
    });
    });
    });
    jQuery("#vflip").click(function(){
    jQuery("#hflip").attr("disabled","true");
    jQuery("#vflip").attr("disabled","true");
    jQuery("#animate_image").animate({
    height:"-=130px",
    top:"+=65"
    },2000,function(){
    jQuery("#animate_image").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsEvDt3shkMqDFwlnKfrWq_pl3Dr2PyVGts1cez_J8Q-ScKSq2wWDEaug946yiDHip05j_48sx4SUXIpU0gUs7hctvYMCP5vgCV29zwEotFK1bhdGdQBFikxw9uXo1fJj7apTdGrip_7QP/s1600/hadat2.jpg").animate({
    height:"+=130px",
    top:"-=65"
    },2000,function(){
    jQuery("#animate_image").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsEvDt3shkMqDFwlnKfrWq_pl3Dr2PyVGts1cez_J8Q-ScKSq2wWDEaug946yiDHip05j_48sx4SUXIpU0gUs7hctvYMCP5vgCV29zwEotFK1bhdGdQBFikxw9uXo1fJj7apTdGrip_7QP/s1600/hadat2.jpg").animate({
    height:"-=130px",
    top:"+=65"
    },2000,function(){
    jQuery("#animate_image").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3S53eiH_TNlJT1OWhjrzjXlyll4u1ntN2KDDck0fNS1sS9b3fhKEclthS8eYA8EJK4VuTwXLgfPiFjEazLqfuEOFAmxoZRJqJ8MqNR1FLlYRMXMIchZe-eq792uEJTaDKB_bx5R8PQO7R/s320/hadat.jpg").animate({
    height:"+=130px",
    top:"-=65"
    },2000,function (){
    jQuery("#vflip").removeAttr("disabled");
    jQuery("#hflip").removeAttr("disabled");
    });
    });
    });
    });
    });

    });
    </script>
    <style>
    #animate_div {
    width:130px;
    height:130px;
    max-height:130px;
    max-height:130px;
    margin-top:10px;
    }
    #animate_div img{
    display:block;
    position:absolute;
    width:130px;
    height:130px;
    }
    </style>
    <input type="button" value="animate 1" id="hflip"/>
    <input style="margin-left:10px;" type="button" value="animate 2" id="vflip"/>
    <div id="animate_div">
    <img id="animate_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3S53eiH_TNlJT1OWhjrzjXlyll4u1ntN2KDDck0fNS1sS9b3fhKEclthS8eYA8EJK4VuTwXLgfPiFjEazLqfuEOFAmxoZRJqJ8MqNR1FLlYRMXMIchZe-eq792uEJTaDKB_bx5R8PQO7R/s320/hadat.jpg"/>
    </div>
    <div>

    Demo

Thứ Bảy, 31 tháng 7, 2010

jQuery - effect

Trong bài này sẽ giới thiệu một số phương thức tạo và quản lý hiệu ứng mà jQuery đã cung cấp.
  • slideUp( [thời gian], [hàm thực thi khi hiệu ứng thực hiện xong])
  • slideDown( [thời gian], [hàm thực thi khi hiệu ứng thực hiện xong])
  • fadeIn( [thời gian], [hàm thực thi khi hiệu ứng thực hiện xong])
  • fadeOut( [thời gian], [hàm thực thi khi hiệu ứng thực hiện xong])
  • Các phương thức này có thể có hoặc không có tham số. Ngoài ra, ta có thể dùng chuỗi "slow" and "fast" để qui định thời gian cho hiệu ứng.

Code
<div>
<style>
#effect_div_border{
display:block;
width:600px;
height:180px;
}
#effect_div{
display:block;
}
#effect_div img{
width:130px;
height:130px;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
var fade = false;
var slide = false;
jQuery("#fadein").click(function(){
if (fade){
jQuery("#effect_div").fadeIn();
fade=!fade;
jQuery("#fadeout").removeAttr("disabled");
jQuery("#fadein").attr("disabled","true");
}
});
jQuery("#fadeout").click(function(){
if (!fade){
jQuery("#effect_div").fadeOut();
fade=!fade;
jQuery("#fadein").removeAttr("disabled");
jQuery("#fadeout").attr("disabled","true");
}
});
jQuery("#slideup").click(function(){
if(!slide){
jQuery("#effect_div").slideUp();
slide=!slide;
jQuery("#slidedown").removeAttr("disabled");
jQuery("#slideup").attr("disabled","true");
}
});
jQuery("#slidedown").click(function(){
if(slide){
jQuery("#effect_div").slideDown();
slide=!slide;
jQuery("#slideup").removeAttr("disabled");
jQuery("#slidedown").attr("disabled","true");
}
});
});
</script>
<div id="effect_div_border">
<input type="button" id="fadein" value="Fade In" disabled/>
<input type="button" id="fadeout" value="Fade Out"/>
<input type="button" id="slideup" value="Slide Up"/>
<input type="button" id="slidedown" value="Slide Down" disabled/>
<div id="effect_div">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTslH7dYz31POh8LP3t6M0ZCQY4UOTf23zr_KvD__QwprE4pAZY_CZE3vWmD4C-A1u0mkf6YzHAS8iWBjNLxGjb_QOpg08CI4BhQ9pyJfHuDftEwh4JXdOJJOf9ygryyrOJY1PRgbIRBIc/s320/thSesshomaruChibi.jpg"/>
</div>
</div>
</div>
Demo
  • show
  • hide
  • toggle
  • slideToggle
Code
<div>
<style>
#effect_div_border{
display:block;
width:600px;
height:180px;
}
.effect_div{
display:block;
}
.effect_div img{
width:130px;
height:130px;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
var show = false;
jQuery("#show").click(function(){
if (show){
jQuery("#show-hide").show();
show=!show;
jQuery("#hide").removeAttr("disabled");
jQuery("#show").attr("disabled","true");
}
});
jQuery("#hide").click(function(){
if (!show){
jQuery("#show-hide").hide();
show=!show;
jQuery("#show").removeAttr("disabled");
jQuery("#hide").attr("disabled","true");
}
});
jQuery("#toggle").click(function(){
jQuery("#show-hide").toggle();
});
jQuery("#slidetoggle").click(function(){
jQuery("#show-hide").slideToggle();
});
});
</script>
<input type="button" id="show" value="Show" disabled/>
<input type="button" id="hide" value="Hide"/>
<input type="button" id="toggle" value="Toggle"/>
<input type="button" id="slidetoggle" value="Slide Toggle"/>
<div id="effect_div_border">
<div class="effect_div" id="effect_div">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTslH7dYz31POh8LP3t6M0ZCQY4UOTf23zr_KvD__QwprE4pAZY_CZE3vWmD4C-A1u0mkf6YzHAS8iWBjNLxGjb_QOpg08CI4BhQ9pyJfHuDftEwh4JXdOJJOf9ygryyrOJY1PRgbIRBIc/s320/thSesshomaruChibi.jpg"/>
</div>
</div>
</div>
Demo

Thứ Hai, 26 tháng 7, 2010

jQuery - mouse hover

Bài viết này đưa ra một ví dụ đơn giản về cách sử dụng event mouse hover trong jQuery. Chúng ta thường sử dụng hover của css để thay đổi style của một element. Nếu ta muốn những xử lý phức tạp được thực thi khi hover thì css không thể đáp ứng được => Vậy ta phải tự viết.

Syntax: .hover(MouseInFunction, MouseOutFunction)

  • MouseInFunction: Hàm được gọi tới khi con trỏ di chuyển vào element.
  • MouseOutFunction: Hàm được gọi tới khi con trỏ di chuyển ra khỏi element.

Ví dụ: Khi di chuyển con trỏ chuột vào ảnh thì ảnh sẽ được phóng to ra, khi con trỏ chuột rời khỏi ảnh kích thước ảnh trở lại như cũ.


Code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("[name='hover_image']").css("top",(jQuery("#hover_div").position().top + 20)+"px");
var left = 40;
jQuery("[name='hover_image']").each(function(i,val){
jQuery(this).css("left",(jQuery("#hover_div").position().left + left)+"px");
left+=100;
});
jQuery("[name='hover_image']").hover(function(){//ham callback hoverIn
jQuery(this).animate({
width:"+=20",
height:"+=20",
left:"-=10",
top:"-=10",
opacity:"1",
filter:"alpha(opacity=100)"
},300);
},function(){//ham callback hoverOut
jQuery(this).animate({
width:"-=20",
height:"-=20",
left:"+=10",
top:"+=10",
opacity:"0.4",
filter:"alpha(opacity=40)"
},300);
});
});
</script>
<style>
#hover_div img{
float:left;
position:absolute;
width:60px;
height:60px;
opacity:0.4;
filter:alpha(opacity=40)
}
</style>
<div id="hover_div" style="height:120px;background-color:#FBF9EA;border:1px solid black;">
<img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
<img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
<img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
</div>

Demo


Thứ Sáu, 16 tháng 7, 2010

jQuery - Selector

jQuery selector là gì?

jQuery selector là một cách gọi đến một hoặc nhiều đối tượng có một số đặc tính nhất định.
Ví dụ: gọi theo name, loại element, theo class,...

Các selector căn bản:

  1. #element_id: Trả về một đối tượng có thuộc tính id được truyền vào.
  2. [name='element_name']: Trả về một nhóm đối tượng có thuộc tính name được truyền vào.
  3. element_type: Trả về một nhóm đối tượng cùng một loại. VD:
    • jQuery("div") sẽ trả về toàn bộ các đối tượng là thẻ div.
    • jQuery("form input") sẽ trả về toàn bộ các đối tượng là thẻ input nằm trong thẻ form.
    • jQuery("#form_id input) sẽ trả về toàn bộ các đối tượng là thẻ input nằm trong thẻ form có id là id truyền vào.

  4. Kết hợp: cách gọi này gần giống như css sẽ tính từ trái sang phải theo thứ tự cha con.
    • jQuery("#test_table tr") trả ra toàn bộ các thẻ tr của table có id là test_table.
    • jQuery("div span") trả ra toàn bộ các thẻ span là con của thẻ div.
    • jQuery("div p span") trả ra toàn bộ các thẻ span thẻ con của p và p phải là thẻ con của div.

Một số phần mở rộng của selector:

  1. .class_name : Thường dùng với selector theo name và type. Trả ra một nhóm các đối tượng có class name tương ứng. VD:
    • jQuery("div.test") sẽ trả ra một nhóm các đối tượng là thẻ div có thuộc tính class là test.
    • jQuery("#my_ul li.select") trả ra một nhóm các đối tượng là thẻ li có class là select và thẻ li là con của thẻ ul có id là my_ul.
  2. :selected : Dùng để lấy ra các đối tượng có thuộc tính selected là true. VD:
    • jQuery("option:selected") sẽ trả ra một nhóm các option có thuộc tính selected bằng true.
  3. :checked : Thường dùng với checkbox và radio để lấy ra những đối tượng được checked. VD:
    • jQuery("[name='checkbox_list_name']:checked") sẽ trả ra một nhóm các checkbox theo tên truyền vào có thuộc tính checked bằng true.
    • jQuery("[name='radio_name']:checked") sẽ trả ra một nhóm các radio theo tên truyền vào có thuộc tính checked bằng true.
  4. :disabled :Trả về các thẻ có thuộc tính disabled. VD:
    • jQuery(":disabled") trả về toàn bộ các thẻ có thuộc tính disabled.
    • jQuery("input:disabled") trả về toàn bộ các thẻ input có thuộc tính disabled.
    • jQuery("form input:disabled") trả về toàn bộ các thẻ input nằm trong thẻ form có thuộc tính disabled.
  5. :odd : Trả về các thẻ có số thứ tự lẻ của đối tượng được chọn. VD:
    • jQuery("li:odd") trả về toàn bộ các thẻ li trên toàn trang web có thứ tự lẻ(1, 3, 5...).
    • jQuery("#ul_list li:odd") trả về toàn bộ các thẻ li con của đối tượng có id là ul_list có thứ tự lẻ.
    • jQuery("tr:odd") trả về toàn bộ các thẻ tr trên toàn trang web có thứ tự lẻ(1, 3, 5..).
    • jQuery("#mytable tr:odd") trả về toàn bộ các thẻ tr con của đối tượng có id là mytable có thứ tự lẻ.
  6. :even : Trả về các thẻ có số thứ tự chẵn của đối tượng được chọn. VD:
    • jQuery("li:even") trả về toàn bộ các thẻ li trên toàn trang web có thứ tự chẵn(2, 4, 6...).
    • jQuery("#ul_list li:even") trả về toàn bộ các thẻ li con của đối tượng có id là ul_list có thứ tự chẵn.
    • jQuery("tr:even") trả về toàn bộ các thẻ tr trên toàn trang web có thứ tự chẵn(2, 4, 6...).
    • jQuery("#mytable tr:even") trả về toàn bộ các thẻ tr con của đối tượng có id là mytable có thứ tự chẵn.

Thứ Sáu, 9 tháng 7, 2010

jQuery - hàm xử lý style

Bài viết này nói về một số hàm dùng để can thiệp vào style của một element.
  1. css: Dùng để lấy giá trị của một property của element trên website hoặc thiết lập giá trị cho css cho property.
    • .css (css property name): trả về giá trị của một property.
    • .css (css property, value): thiết lập giá trị cho một css property của element.
    • .css ( {list of properties} ): dùng để thiết lập một nhóm các thuộc tính css.
    • Tình huống: Thay đổi CSS cho ô vuông màu xám:
      • Nút Get: lấy ra giá trị của thuộc tính background-color.
      • Nút Set: thay đổi giá trị background-color.
      • Nút Group sẽ gán lại nhóm giá trị background-color, width, height.
    Code
    <div>
    <style>
    #css_left {
    border:1px solid black;
    background-color:gray;
    width:200px;
    height:200px;
    float:left;
    }
    #css_right {
    float:left;
    margin-left:50px;
    width:200px;
    height:200px;
    }
    </style>
    <script type="text/javascript">
    jQuery(document).ready(function(){
    jQuery("#butGet").click(function(){
    alert("background-color: " + jQuery("#css_left").css("background-color"));
    });
    jQuery("#butSet").click(function(){
    jQuery("#css_left").css("background-color","red");
    });
    jQuery("#butGroup").click(function(){
    jQuery("#css_left").css({"background-color":"green","width":"100px","height":"100px"});
    });
    });
    </script>
    <div id="css_left"></div>
    <div id="css_right">
    <input type="button" value="Get" id="butGet"/>
    <input type="button" value="Set" id="butSet"/>
    <input type="button" value="Group" id="butGroup"/>
    </div>
    <div style="clear:both;"></div>
    </div>

    Demo




  2. Các hàm thao tác với Attribute của một element.
    • attr: Dùng để lấy giá trị của một attribute của element hoặc gán giá trị cho một attribute.
      • .attr (attribute name): trả về giá trị của một attribute của một element.
      • .attr (attribute name, value): thiết lập giá trị cho một attribute của element.
      • .attr ( {list of properties} ): dùng để thiết lập một nhóm các attribute cho element.
    • removeAttr: Dùng để gở bỏ một attribute của một element.
      • .removeAttr (attribute name): gỡ bỏ một attribute ra khỏi một element.
    Tình huống: Thay đổi attribute cho ảnh (thẻ img)
    • Nút Get: lấy ra giá trị trong attribute src của thẻ img bên trái.

    • Nút Set One Attribute: Gán lại giá trị cho attribute src của thẻ img(đổi hình hiển thị).

    • Nút Set Group Attribute: Gán lại giá cho các attribute src, title, alt của ảnh. Để kiểm tra bạn rê chuột vào ảnh sẽ thấy hiện lên dòng tooltip sesshomaru image

    • Nút Remove Attribute: Gỡ bỏ thuộc tính title của ảnh( rê chuột vào ảnh để kiểm tra ảnh sẽ mất đi dòng tooltip).
    Code
    <div>
    <style>
    #attr_left {
    background-color:gray;
    width:122px;
    height:122px;
    float:left;
    }
    #attr_right {
    float:left;
    margin-left:50px;
    width:122px;
    height:122px;
    }
    </style>
    <script type="text/javascript">
    jQuery(document).ready(
    function(){jQuery("#butGetAttr").click(function(){
    alert("image src: " + jQuery("#myImage").attr("src"));
    });
    jQuery("#butOneAttr").click(function(){
    jQuery("#myImage").attr("src","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNdfLpTMuoC9TvQ81iExZGTW-uZ2EyLHFDk44mer6ZbAoCHLaN_hKAiO4RnN_erOSN6TVpHFpO_DswfpqeYcpG3ybX4VIywyk0N2rs767O6yV-Ouc_fax9CqiKs5iuunm6AQaN2gTv1vXK/s320/sesshomaru.jpeg");
    });
    jQuery("#butGroupAttr").click(function(){
    jQuery("#myImage").attr({src:"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTslH7dYz31POh8LP3t6M0ZCQY4UOTf23zr_KvD__QwprE4pAZY_CZE3vWmD4C-A1u0mkf6YzHAS8iWBjNLxGjb_QOpg08CI4BhQ9pyJfHuDftEwh4JXdOJJOf9ygryyrOJY1PRgbIRBIc/s320/thSesshomaruChibi.jpg",title:"Sesshomaru image",alt:"jquery attr image"});
    });
    jQuery("#butRemoveAttr").click(function(){
    jQuery("#myImage").removeAttr("title");
    });
    });
    </script>
    <div id="attr_left">
    <img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTslH7dYz31POh8LP3t6M0ZCQY4UOTf23zr_KvD__QwprE4pAZY_CZE3vWmD4C-A1u0mkf6YzHAS8iWBjNLxGjb_QOpg08CI4BhQ9pyJfHuDftEwh4JXdOJJOf9ygryyrOJY1PRgbIRBIc/s320/thSesshomaruChibi.jpg" border="0" alt=""id="myImage" />
    </div>
    <div id="attr_right">
    <input type="button" value="Get" id="butGetAttr"/>
    <input type="button" value="Set One Attribute" id="butOneAttr"/>
    <input type="button" value="Set Group Attribute" id="butGroupAttr"/>
    <input type="button" value="Remove Attribute" id="butRemoveAttr"/>
    </div>
    <div style="clear:both;"></div>
    </div>

    Demo





  3. Các hàm thao tác về class
    • .addClass (class name): Dùng để gán một class cho một element.
    • .removeClass (class name): gỡ bỏ class ra khỏi attribute class của element.
    Tình huống: Thay đổi class cho table
    • Nút Odd: dòng lẻ trong table sẽ xuất hiện màu nền vàng nhạt cho dòng đó.
    • Nút Even: dòng chẵn trong table sẽ xuất hiện màu nền xanh nhạt cho dòng đó.
    • Nút Reverse: đảo ngược hai class của dòng chẵn và lẻ.
    Code
    <div>
    <b>Demo</b>
    <style>
    #table_left{
    float:left;
    }
    #button_right{
    float:left;padding-left:50px;
    }
    #my_table{
    border-collapse:collapse;
    border:1px solid black;
    width:400px;
    }
    #my_table tr th{
    border:1px solid black;
    }
    #my_table tr td{
    border:1px solid black;
    }
    .odd{
    background-color:rgb(249,250,192);
    color:red;
    font-weight:bold;
    }
    .even{
    background-color:rgb(200,251,179);
    color:blue;
    }
    </style>
    <script type="text/javascript">
    jQuery(document).ready(function(){
    var odd = false;
    var even = false;
    jQuery("#butReverse").attr("disabled","true");
    jQuery("#butOdd").removeAttr("disabled","true");
    jQuery("#butEven").removeAttr("disabled","true");
    jQuery("#butOdd").click(function(){
    if (!odd){
    odd = !odd;
    jQuery("#my_table").find("tr:odd").addClass("odd");
    if (even){
    jQuery("#butReverse").removeAttr("disabled");
    jQuery("#butOdd").attr("disabled","true");
    jQuery("#butEven").attr("disabled","true");
    }
    }
    });
    jQuery("#butEven").click(function(){
    if (!even){
    even = !even;
    jQuery("#my_table").find("tr:even").addClass("even");
    if (odd){
    jQuery("#butReverse").removeAttr("disabled");
    jQuery("#butOdd").attr("disabled","true");
    jQuery("#butEven").attr("disabled","true");
    }
    }
    });
    jQuery("#butReverse").click(function(){
    jQuery("#my_table").find("tr:even").removeClass("even");
    jQuery("#my_table").find("tr:odd").removeClass("odd");
    jQuery("#my_table").find("tr:even").addClass("odd");
    jQuery("#my_table").find("tr:odd").addClass("even");
    });
    });
    </script>
    <div id="table_left">
    <table id="my_table">
    <tr style="background-color:black;color:white;">
    <th>STT</th><th>Họ và tên</th><th>Ngày sinh</th><th>Giới tính</th>
    </tr>
    <tr>
    <td>1</td><td>Nguyễn Van A</td><td>01/01/1989</td><td>Nam</td>
    </tr>
    <tr>
    <td>2</td><td>Trần Van B</td><td>01/08/1989</td><td>Nam</td>
    </tr>
    <tr>
    <td>3</td><td>Trương Thị C</td><td>05/01/1989</td><td>Nữ</td>
    </tr>
    <tr>
    <td>4</td><td>Phạm Thị D</td><td>02/06/1989</td><td>Nữ</td>
    </tr>
    <tr>
    <td>5</td><td>Lê Văn E</td><td>03/07/1989</td><td>Nam</td>
    </tr>
    </table>
    </div>
    <div id="button_right"><input type="button" value="Odd" id="butOdd" style="width:75px;"/>
    <input type="button" value="Even" id="butEven" style="width:75px;"/>
    <input type="button" value="Reverse" id="butReverse" style="width:75px;" disabled/></div>
    <div style="clear:both;"></div>
    </div>

    Demo
    STTHọ và tênNgày sinhGiới tính
    1Nguyễn Văn A01/01/1989Nam
    2Trần Văn B01/08/1989Nam
    3Trương Thị C05/01/1989Nữ
    4Phạm Thị D02/06/1989Nữ
    5Lê Văn E03/07/1989Nam





Một số câu hỏi thường gặp

  1. Sự khác nhau giữa hàm css và hàm addClass?
  2. Điểm khác nhau cơ bản nhất là hàm addClass thao tác trên attribute class của một element trong khi đó hàm css thao tác trên attribute style.

  3. Tại sao addClass rồi mà element vẫn không thay đổi ?
  4. Bạn nên kiểm tra lại style của element vì class có độ ưu tiên thấp hơn style. Ở ví dụ phía trên dòng tr đầu tiên có attribute style cố định do đó khi addClass vào các dòng lẻ các properties của class không thể đè lên được các properties trong attribute style được vì độ ưu tiên thấp hơn.

  5. Dùng hàm css để add một property cho một element vậy có cách nào remove property đó ra hay không?
  6. Câu trả lời là không. Do hàm css thao tác trên attribute style do đó khi đã add một property vào rồi thì bạn không thể remove nó ra mà chỉ có thể thay đổi giá tri của nó. Nếu muốn remove được thì tốt nhất là định nghĩa hai class khác nhau và sử dùng hàm addClass và removeClass.

  7. Tại sao dùng hàm addClass nhiều lần thì thuộc tính class không đổi?
  8. Do hàm addClass thao tác trên attribute class của element. Trên attribute class có thể tồn tại song song nhiều class khác nhau. Do đó khi dùng liên tiếp thì nó sẽ tự động thêm class vào và các properties trong hai class sẽ được overwrite lẫn nhau. VD: class="class1" dùng tiếp hàm addClass("class2") ta sẽ có class="class1 class2"

Thứ Ba, 6 tháng 7, 2010

jQuery - other event

Bài viết này giới thiệu một số kinh nghiệm cơ bản về một số sự kiện(event) khác trong jQuery.
  1. change: Thường dùng cho checkbox hoặc radio button.
  2. Tình huống: Check vào một checkbox hoặc một radio button bên trái, ô vuông xám bên phải sẽ hiển thị danh sách những checkbox hoặc radio nào được chọn.
    Code
    <div>
      <style>
      #change_table tr td div{
        width:200px;
        height:100px;
        background-color:#EAEAEA;
        border:1px solid black;
      }
      </style>
      <script type="text/javascript">
      jQuery(document).ready(function(){
        jQuery("[name='cks']").change(function(){
        var str="";
        jQuery("input[name='cks']:checked").each(function(i,val){
          str += jQuery(this).val() + " duoc checked, ";
        });
        jQuery("#cks_div").html(str);
        });
        jQuery("[name='rds']").change(function(){
        var str="";
        jQuery("input[name='rds']:checked").each(function(i,val){
          str += jQuery(this).val() + " duoc checked, ";
        });
        jQuery("#rds_div").html(str);
        });
      });
      </script>
      <table id="change_table"><tr>
        <td>
        <input type="checkbox" value="checkbox 1" name="cks">checkbox 1
        </input>
        <input type="checkbox" value="checkbox 2" name="cks">checkbox 2
        </input>
        <input type="checkbox" value="checkbox 3" name="cks">checkbox 3
        </input>
        <input type="checkbox" value="checkbox 4" name="cks">checkbox 4
        </input>
        </td>
        <td><div id="cks_div">Không có checkbox nào được check.</div></td>
      </tr>
      <tr>
        <td>
        <input type="radio" value="radio 1" name="rds">radio 1</input>
        <input type="radio" value="radio 2" name="rds">radio 2</input>
        <input type="radio" value="radio 3" name="rds">radio 3</input>
        <input type="radio" value="radio 4" name="rds">radio 4</input>
      </td>
        <td><div id="rds_div">Không có radio button nào được chọn.</div>
        </td>
      </tr>
      </table>
    </div>
    Demo
    checkbox 1
    checkbox 2
    checkbox 3
    checkbox 4
    Không có checkbox nào được check.
    radio 1
    radio 2
    radio 3
    radio 4
    Không có radio button nào được chọn.

  3. focus và blur
  4. Tình huống: Kiểm tra độ mạnh của password. Có 4 loại kí tự: kí tự thường, kí tự hoa, số, các kí tự đặc biệt. Điều kiện:
    • very weak: Thỏa 1 trong 4 loại kí tự.
    • weak: Thỏa 2 trong 4 loại kí tự.
    • medium: Thỏa 3 trong 4 loại kí tự.
    • strong: thỏa 4 loại kí tự.
    • Mật khẩu rỗng: sẽ hiển thị thông báo yêu cầu nhập.
    Code
    <div>
      <style>
      #pass_test:focus{
        background-color:black;
        color:white;
      }
      </style>
      <script type="text/javascript">
      jQuery(document).ready(function(){
        jQuery("#pass_test").focus(function(){
          jQuery("#pass_none").hide();
          jQuery("#pass_strength").html("very weak");
          jQuery("#pass_strength").fadeIn();
        });
        jQuery("#pass_test").blur(function(){
          if(jQuery("#pass_test").val()==""){
            jQuery("#pass_strength").hide();
            jQuery("#pass_none").fadeIn();
          }
        });
        jQuery("#pass_test").keyup(function(){
          var input = jQuery(this).val();
          var strongRegex = new RegExp("^(?=.*[^a-zA-Z0-9_])(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$", "g");
          var mediumRegex = new RegExp("^(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9_]))|((?=.*[a-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9_]))|((?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9_]))).*$", "g");
          var enoughRegex = new RegExp("^(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[^a-zA-Z0-9_]))|((?=.*[A-Z])(?=.*[^a-zA-Z0-9_]))|((?=.*[0-9])(?=.*[^a-zA-Z0-9_]))).*", "g");
          if (strongRegex.test(input)){
            jQuery("#pass_strength").html("strong");
          }else if (mediumRegex.test(input)){
            jQuery("#pass_strength").html("medium");
            }else if (enoughRegex.test(input)){
              jQuery("#pass_strength").html("weak");
              }else{
                jQuery("#pass_strength").html("very weak");
              }
        });
      });
      </script>
      <table>
        <tr>
          <td>
            <input type="text" id="pass_test"/>
          </td>
          <td>
            <div id="pass_strength" style="display:none"></div>
            <div id="pass_none" style="display:none">Vui lòng nh?p m?t kh?u.</div>
          </td>
        </tr>
      </table>
    </div>
    Demo

  5. live và bind: Thường dùng cho các để khai báo các hàm callback cho các sự kiện của một element
  6. Giống nhau
    • Cú pháp: objects.bind(event name, callback function),objects.live(event name, callback function)
    • Có thể khai báo 1 hàm callback cho nhiều event cùng lúc. VD: bind("click mousedown mouseup",callback function)
    Khác nhau
    • Hàm bind bắt buộc phải được sử dụng trong function callback của sự kiện ready của document. Hàm live không bắt buộc điều đó.
    • VD: $(document).ready(function(){ $("#element_id").bind(event name,callback)});
    Code
    <div>
      <style>
      #bind_left{
        width:200px;
        height:200px;
        float:left;
        background-color:#D0D0D0;
      }
      #bind_right{
        width:200px;
        height:200px;
        float:left;
        margin-left:50px;
        background-color:#EAEAEA;
        overflow:auto;
      }
      </style>
      <script type="text/javascript">
      jQuery(document).ready(function(){
        jQuery("#bind_left").bind("mousedown mouseup click",function(e){
          jQuery("#bind_right").html(jQuery("#bind_right").html()+ " " + e.type);
        });
      });
      jQuery("#bind_left").live("mouseover mouseout",function(e){
        jQuery("#bind_right").html(jQuery("#bind_right").html()+ " " + e.type);
      });
      </script>
      <div id="bind_left"></div>
      <div id="bind_right"></div>
      <div style="clear:both;"></div>
    </div>
    Demo

  7. scroll: Dùng để bắt sự kiện của thanh cuộn.
  8. Code
    <div><script type="text/javascript">
    $(document).ready(function() {
    jQuery(window).scroll(function(){
    if (jQuery(window).scrollTop()>0)
    {
    jQuery("#back").removeAttr("disabled");
    }
    else{
    jQuery("#back").attr("disabled",true);
    }
    });
    jQuery("#back").click(function(){
    var j = 0;
    var len = jQuery(window).scrollTop()/20;
    for (var i = jQuery(window).scrollTop(); i>=0;i-=len)
    {
    (i>0)? j = i:j = 0;
    jQuery(window).scrollTop(j).delay(5);
    }
    });
    });
    </script><div style="position:fixed;z-index:190;bottom:0;right:0px;"><input id="back" type="button" value=">>Back to top<<" /></div></div>
    Demo
    Tạo Button Back To Top đơn giản nằm ở góc phải màn hình. Chỉ khi nào có thể scroll lên đầu trang được thì button mới được enable lên.