开发者

html dynamically add event listeners without knowing id

I am creating lots of select lists ( drop downs) when I build the page. The drop downs are based on external data files, so I set the id's at runtime. Somet开发者_StackOverflow社区hing like

<% name="TypeA" + specialIDString %>
<select  id="<%= name %>" >
blah
blah 
</select>

How do I then add an event listener, since I don't know the ID ahead of time? Can I search the DOM for all id's with "TypeA" in the id, and just add a listener to each one of them?

I know how to trigger an onLoad() method in javascript, after the page is loaded, I just want to know how to search the DOM to find ID's with a particular string in them. Thanks.


Just for the record, the vanilla JavaScript answer:

function getElementsByIdStartsWith( type, idStartsWith ) {
    var arr = [],
        all = document.getElementsByTagName( type );

    for ( var i = 0; i < all.length; i++ ) {
        if ( all[i].id.indexOf( idStartsWith ) === 0 ) {
            arr.push( all[i] );
        }
    }

    return arr;
}

and then:

var selects = getElementsByIdStartsWith('select', 'TypeA');

Now you can use for loop to bind handlers to each element from the array.


If you use jQuery you can do this simply like:

$('select[id^=TypeA]').bind('yourevent', function() {});


You can add the event listener inline and directly pass the element.

<select onclick="myfunction(this)" id="<%= name %>" >
blah
blah 
</select>

Another thing you can do is pass the event attribute like this:

<select onclick="myfunction(event)" id="<%= name %>" >
blah
blah 
</select>

Then in myfunction, event.target will be the element that triggered the call. You could get the id with event.target.id.


If you can't know the ID specifically there are other things you can do.

One choice is to use a class name; another option is to prepend the ID with something static and (in jquery parlance) your can use a starts-with selector.

<select id="generated<%=name%>">

var mySelect = $('select[id^=generated]');

It will work but its not the best way of doing things, especially if you'll have more than one generated element. It's also relatively slow.

Selecting by CSS Class name would probably be the best way.


if you have jQuery its easy with jQuery query selector. but if not:

  1. Add a class to your element:

    <% class="myClass" name="TypeA" + specialIDString %>
    <select  id="<%= name %>" >
        blah
        blah 
    </select>
    
  2. Use getElementsByClassName to reach your elements

    var myElems = document.getElementsByClassName('myClass');
    
  3. Loop around elements and add event listener

    for(var i=0; i<myElems.length;  i++){
        myElems[i].addEventListener('click', function(){}, false);
    }
    

I know getElementsByClass name don't work in IE6 (or 7 also?). But this is my solution. Maybe I can update it with x-browser solution

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜