Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate event handlers with loop in Javascript? [duplicate]

Tags:

For example, I have 10 a tags generated from an AJAX response:

<a href="#" id="b1">b1</a> <a href="#" id="b2">b2</a> <a href="#" id="b3">b3</a> <a href="#" id="b4">b4</a> <a href="#" id="b5">b5</a> <a href="#" id="b6">b6</a> <a href="#" id="b7">b7</a> <a href="#" id="b8">b8</a> <a href="#" id="b9">b9</a> <a href="#" id="b10">b10</a> 

I need to assign onclick event to each of them via loop:

for(i=1; i<11; i++) {     document.getElementById("b"+i).onclick=function() {         alert(i);     } } 

This doesn't work, it only assigns onclick to the last a tag and alerts "11". How can I get this to work? I'd prefer not to use jQuery.

like image 334
Caballero Avatar asked Jun 26 '11 23:06

Caballero


People also ask

How do you add multiple event handlers?

The addEventListener() method You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

Can we have more than one event handler method for same event?

One event can have more than one event handler method in the same class or in different classes. At the run time only one handler method will be triggered at a time. After triggering the one that has to be deactivated and then another handler method will have to be registered to be triggered.

What is JavaScript Eventhandler?

Event handlers are the JavaScript code that invokes a specific piece of code when a particular action happens on an HTML element. The event handler can either invoke the direct JavaScript code or a function.


2 Answers

All of your handlers are sharing the same i variable.

You need to put each handler into a separate function that takes i as a parameter so that each one gets its own variable:

function handleElement(i) {     document.getElementById("b"+i).onclick=function() {         alert(i);     }; }  for(i=1; i<11; i++)      handleElement(i); 
like image 179
SLaks Avatar answered Sep 19 '22 03:09

SLaks


A closure is what you're looking for:

for(i=1; i<11; i++) {     (function(i) {         document.getElementById("b"+i).onclick=function() {             alert(i);         };     })(i); } 
like image 40
Kevin Avatar answered Sep 19 '22 03:09

Kevin