官术网_书友最值得收藏!

Finding a group of elements by their class attribute

Collections of HTML elements may be handled as a group.

Getting ready

A favorite trick is to turn the option elements of a select on and off. Using various collections of elements, this is a snap in MooTools.

How to do it...

Use ID attributes to affect unique elements: $('my_single_target'), and use class attributes to affect groups of elements: $$('.my_target_class').

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<form action="javascript:" method="get">
Choose an Animal:<br/>
<select id="animal">
<option value="">Select Animal</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="pig">Pig</option>
</select>
// some browsers do not fire select onchange
// until focus changes
<input type="button" value="Select Animal"/>
<br/><br/>
<select id="animal_items">
<!-- cat options -->
<option class="nopeek cat" value="1">Ball of String</option>
<option class="nopeek cat" value="2">Fake Mouse</option>
<option class="nopeek cat" value="3">Catnip (mmm)</option>
<!-- dog options -->
<option class="nopeek dog" value="4">Juicy Bone</option>
<option class="nopeek dog" value="5">Bouncy Ball</option>
<option class="nopeek dog" value="6">Rope w/ Handle</option>
<!-- pig options -->
<option class="nopeek pig" value="7">Mud</option>
<option class="nopeek pig" value="8">Slop</option>
<option class="nopeek pig" value="9">Water Hose</option>
</select>
</form>
<noscript>JavaScript is disabled.</noscript>
<script type="text/javascript">
// get a collection of elements so we can hide them onchange
var all = $$('.nopeek');
all.setStyle('display','none');
$('animal').addEvent('change',function pare_options() {
all.setStyle('display','none');
var animal_chosen = $('animal').get('value');
$$('.'+animal_chosen).setStyle('display','block');
});
</script>

How it works...

Our first select has a group of choices where each value represents a class that is given to groups of option elements in the second drop-down menu. When the first widget is changed, the onChange event calls the bound anonymous function and uses the class all to turn off the visibility of all option elements then uses the class value chosen to pare down the selection options.

There's more...

When dealing with select elements, be prepared for browser quirks especially the actual timing of the onChange event. Here we have a fake button used solely to cause our user to change the focus off the element so that we are certain the event fires.

主站蜘蛛池模板: 栾城县| 四川省| 阿勒泰市| 东台市| 清河县| 海城市| 龙陵县| 临西县| 怀远县| 安龙县| 蒙城县| 湟源县| 资中县| 巴东县| 张北县| 南京市| 宁都县| 兖州市| 曲靖市| 时尚| 浮山县| 卢龙县| 汶川县| 兴义市| 海晏县| 宁远县| 鹿邑县| 汾阳市| 古交市| 兴海县| 锡林浩特市| 固镇县| 定边县| 清丰县| 徐水县| 长武县| 贵州省| 教育| 布尔津县| 彭阳县| 凤山市|