Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: addEventListener question Date: Sat, 11 Aug 2018 14:53:37 +0100 Organization: A noiseless patient Spider Lines: 56 Message-ID: <87zhxtxb4u.fsf@bsb.me.uk> References: <5b6dbba7$0$2957$e4fe514c@news.xs4all.nl> <5b6ed658$0$2956$e4fe514c@news.xs4all.nl> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="d5684bb80215f18dd6aae09a41c84696"; logging-data="27594"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX186BNDQ47VInB52EGDpTbvretS9H3g7WIw=" Cancel-Lock: sha1:6jsIle24532MoLCy25E93ikb1e0= sha1:JUVw2izgMCtfeAniElQGAxXwVOM= X-BSB-Auth: 1.8e0d59f72b0f35cfe0c8.20180811145337BST.87zhxtxb4u.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:35455 Luuk writes: >> Luuk wrote on 10 Aug 2018 in comp.lang.javascript: >> >>>
>>> >>>
001
>>>
22
>>>
10
>>> >>>
002
>>>
45
>>>
36
(The thanks are to Evertjan.) > Ok, thanks, but i made a small modification, i like 'abc'... ;) > > > var links = document.getElementById('csschart').children; > var index; > var abc = -1; > for (index = 0; index < links.length; ++index) { > if (links[index].tagName=='DT') { abc++; } > links[index].classList.add("__nr" + abc); > links[index].addEventListener('click',function(e) { > alert(this.classList.toString().replace(/.*__nr/, '')); > }); > } You appear to be using the class simply to get the right numeric string into the function at execution time. There are other, less contrived ways to do that, but you already have the string, don't you, in the
...
element? Also, with the code as it is, you don't need fresh a listener function every time. You just need two of them, each used three times. Of course, in your final version that might not be the case -- I can only go by what you have written so far. Here's one approach: var links = document.getElementById('csschart').children; var listener; for (var index = 0; index < links.length; ++index) { if (links[index].tagName == 'DT') { listener = (function (num) { return function (e) { alert(num); } })(links[index].innerText); } links[index].addEventListener('click', listener); } -- Ben.