ก่อนแรกเรียวสร้างอิลิเมนต์ขึ้นมาก่อน
<img src="image1.jpg" name="nameImg1" id="img1" class="thisimg" />
<img src="image2.jpg" name="nameImg2" id="img2" class="thisimg" />
<img src="image3.jpg" name="nameImg3" id="img3" />
จากนั้นเขียน jQuery เพื่อลูปแสดงอิลิเมนต์ออกมา
$(document).ready(function(){
$(".thisimg").each( function(index) {
alert ( "Element at "+index+" have id :"+this.id+" and name ="+this.name+" & class = "+this.className);
});
});
จากโค้ดจะเห็นว่าเรียวลูปโดยอ้างอิงจากชื่อคลาสนั่นคือ .thisimg ซึ่งเรามีอิลิเมนต์ที่ใช้คลาส .thisimg อยู่สองอิลิเมนต์
ทีนี้ลองรันดูนะีคะ
จะเห็นว่าจะแสดง alert ขึ้นมาสองอันเนื่องจากอิลิเมนต์ที่ใช้คลาสที่ชื่อว่า .thisimg มีอยู่สองอันนั่นเอง
เป็นตัวอย่างที่อ่านง่าย และเข้าใจเร็วมากครับ
ตอบลบ