开发者

Attaching an event listener to a collection of items using Prototype

开发者 https://www.devze.com 2023-02-08 09:21 出处:网络
I have a bunch of input boxesand would like to attach a single event listener to all of them. My goal is to 开发者_StackOverflow中文版check if the parent element (span.genre_checkbox) has a class of \

I have a bunch of input boxes and would like to attach a single event listener to all of them. My goal is to 开发者_StackOverflow中文版check if the parent element (span.genre_checkbox) has a class of "active" or not. If it doesn't have a class of active, apply it. If it does have a class of active, remove it.

My code looks like this

<span class="genre_checkbox"><input type="checkbox" /> All Genres<br /></span>
<span class="genre_checkbox"><input type="checkbox" /> Alternative<br /></span>
<span class="genre_checkbox"><input type="checkbox" /> Blues<br /></span>

etc...

$$('.genre_checkbox input').observe('click', function () {
    if ($(this).up().hasClassName('active') == false ) {
        $(this).up().addClassName('active');
    }
    else {
        $(this).up().removeClassName('active');
    }
});

The error I'm getting is:

"$$('.genre_checkbox input').observe is not a function"

I'm not sure why I'm getting the error... do I need to use .each() or .invoke()?


You're going in the right direction, $$ returns an array and you need to set an observer on each of them. One neat way is like this:

$$('.genre_checkbox input').invoke('observe', 'click', function () {
    ...

However it can be improved by taking advantage of the browser's event bubbling. You will need a single common parent element of all the inputs:

<div id="genre_options">
    <span class="genre_checkbox"><input type="checkbox" /> All Genres<br /></span>
    <span class="genre_checkbox"><input type="checkbox" /> Alternative<br /></span>
    <span class="genre_checkbox"><input type="checkbox" /> Blues<br /></span>
</div>

Then the javascript is simpler:

$('genre_options').on('click', 'input', function() {
    ...

The advantage here is only one event is being added, saving time, and only one function is generated, saving memory. Also it's marginally faster to retrieve an element by it's ID instead of by class name, not by much but it's nice to know.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号