/    Sign up×
Community /Pin to ProfileBookmark

dynamically changing events (little help, or some thoughts)

Elo,
I prolly have a solution, but I’m just wondering perhaps someone might
come up with some idea’s..

I’m trying to add events on a div selected by and id.

[CODE]<div id=”test1″></div>
<div id=”test2″></div>
etc..[/CODE]

The ID’s, in this example the divs, are in an array

[CODE]
array = new Array();
array[0] = “test1”;
array[1] = “test2”;
etc..[/CODE]

I have several functions, one for example

[CODE]function test_func(id) {
alert(id);
}
[/CODE]

now i iterate over the id’s to see if they are present, and if so, add an onclick event

[QUOTE]

for(i = 0; i<array.length; i++) {
if(document.getElementById(array[i]) !== null)
document.getElementById(array[i]).onclick = function () { test_func(i) };
}

[/QUOTE]

now the thing is, when i click on a div, i get of course the last number “i” has been, 3. It will always be three, i was just wondering if there is a thing in JavaScript where i can sort of “save” the different id’s in the function “test_func”

As you might have noticed, I’m just starting to get a grip on JavaScript, or at least I’m trying to get the grip ? ..

What i could try is create objects for every div element with an ID i have to inject with events, put the needed functions in an array inside the object, and they can retrieve the necessary variable info from the object .. dunno, just a thought ..

Hope it makes sense,
Cheers

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@dbforchauthorJan 07.2008 — Hmm, found a sort of a solution, it's not nice, but it works ..

instead of using

document.getElementById(array[i]).onclick = function () { test_func(i) };[/QUOTE]



insert the function as string



document.getElementById(array[i]).attributes['onclick'].value = "some_func("+i+")";[/QUOTE]



Well.. it works ..



Cheers
×

Success!

Help @dbforch spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...