Danh mục

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