[thelist] thelist Digest, Vol 63, Issue 12
Howard Jess
hjess at cardomain.com
Wed May 14 15:21:04 CDT 2008
Blake wrote:
> <mwarden at gmail.com> wrote:
> > > On Wed, May 14, 2008 at 12:37 AM, Blake <haswell00 at gmail.com> wrote:
> > > > link[i].setAttribute('onclick', 'swapStories(' + i +
> > >
> > > You can not set onclick using setAttribute. onclick is a javascript
> > > property. Try using the "link[i].onclick =" syntax
>
> Thanks, but I can't think of a way to achieve the functionality I want
> using methods like this. I tried some other solutions first and they
> all had problems which made them un-workable. See below:
>
> for(var i = 0; i < link.length; i++) {
> link[i].onclick = swapStories; // This has the problem that I can't
> pass the argument through so it's useless for me
> }
>
> for(var i = 0; i < link.length; i++) {
> link[i].onclick = function() {
> swapStories(i); // This has the problem that the function isn't run
> until the element is clicked, and since I'm passing a counter the
> value is useless by the time the event triggers
> }
> }
>
> for(var i = 0; i < link.length; i++) {
> link[i].onclick = function(i) {
> swapStories(i); // This seems to pass the MouseEvent through, which
> is useless for me. I just want the counter.
> }
> }
You probably want a closure here:
for (var i=0; i < link.length; i++) {
link[i].onclick = (function(n) {
return function() {swapStories(n)}
})(i);
}
That is, the onclick property is set to the result of the anonymous
function ("(function(n)..."); that result is a function itself,
closed over the value of "i".
[Untested, of course.]
--
hj
More information about the thelist
mailing list