Prototype :: Selector

Posted by PunNeng, Wed Sep 12 01:54:00 UTC 2007

ปฎิเสธไม่ได้ว่าการทำงานกับ Javascript จะต้องเข้าไปยุ่งเกี่ยวกับ DOM อย่างแน่นอน code อย่าง

document.getElementById('id');
// or
document.getElementsByTagName('tag-name');

จะต้องถูกเรียกใช้อย่างแน่นอน
แต่ถ้ามีวิธีที่ง่ายกว่าล่ะ !!!

Selector - Id

$('id')
// $('header');

ตัวอย่าง

$('header').hide();
$('header').show();
// or can set to variable
var header = $('header');
header.hide();

ใน Prototype function hide/show/toggle เป็นอีก function ที่ใช้บ่อยมาก ซึ่งมันจะไปสั่งให้ DOM ก้อนน้ันๆ ทำการเปลี่ยนค่า display ของ style นั่นแหละ ดีกว่าทีี่จะต้องไปใช้ .style.display = value;

จริงๆ สามารถเรียกได้อีกอย่างคือ การเรียกผ่าน Element class

Element.hide('id');

ก็ได้

Selector - Tag name(CSS Selector)

$$('tag-name')
// $$('div#footer');
// $$('li.nav');

มันจะ return มาเป็น array

$$('li.nav').first().hide();
$$('a').invoke('hide');

invoke ไว้ใช้สำหรับการสั่งให้ทุก element ใน array เรียก function ที่เราใส่ไป
หรือจะ loop ในแต่ละ element ก็ได้

$$('a').each( function(element) { element.hide; element...; ...;} )

ประกาศแบบ inline ก็ได้
block หน้าตาแบบนี้ดูคุ้นๆ แฮะ นึกไม่ออกว่าเหมือนภาษาอะไร ;p
มาดูหน้าตาอย่างอื่นต่อ

$$('div#header a, div#footer a')
$$('a[title=back]')
$$('div[id]')

ไม่ว่าจะโลภมาก อยากเลือกที่ละหลายๆ tag หรือว่าจะเลือกโดย attribute หรือแม้กระทั่ง เลือกเฉพาะ tag ที่ประกาศเฉพาะ attribute ก็ทำได้

ข้อมูลจาก api ของ Prototype ครับ

ปล. ยังไม่จบนะครับ

Filed Under: General | Tags: howto javascript prototype selector

Comments

Have your say

A name is required. You may use HTML in your comments.




codegent: we're hiring