Dynamically create an anchor tag

A

Andrew

Well,

I've a little trouble that seems unsolvable. It's a stupid question
that born because IE doesn't respect the standard as its usual.

But go to the problem. I create an anchor tag element, set some
properties, but not all works as it should. This is my code.

var anchorTag = document.createElement('a');
anchorTag.appendChild(document.createTextNode(x));

var pathImg = x.replace(' ', '_').replace('è', 'e');
pathImg = "images/" + pathImg + ".jpg";

anchorTag.href = "#";
anchorTag.setAttribute('onclick', 'popImage("' + pathImg + '", "' + x +
'")');
colorSpan.appendChild(anchorTag);


Doing in this way works fine just for Firefox and other browser. IE,
unfortunately, ignore the setAttribute method name.
The only way I've found to let it work on IE and Firefox too is the
line below.

//anchorTag.onclick = function() { "popImage('" + pathImg + "', '" + x
+ "')" }

Unfortunately, since the code above is nested into a for ... next loop
the code above not assign the pathImg value and x value to the content
of the in-line function but just a reference, and this cause an obvious
problem. All elements onclick event call through the popImage function
the same image.
Is there a way to solve this. Where am I doing mistake?

I've tried using the eval() method without results.

Thanks for any help.
Andrew
 
R

RobG

Andrew said:
Well,

I've a little trouble that seems unsolvable. It's a stupid question
that born because IE doesn't respect the standard as its usual.

The first part is due to an issue of implementation where there is
nothing to explicitly say how things should work. The second part is
about closures.

[...]
The only way I've found to let it work on IE and Firefox too is the
line below.

//anchorTag.onclick = function() { "popImage('" + pathImg + "', '" + x
+ "')" }

Unfortunately, since the code above is nested into a for ... next loop
the code above not assign the pathImg value and x value to the content
of the in-line function but just a reference, and this cause an obvious
problem. All elements onclick event call through the popImage function
the same image.

Yes, because you have a closure back to pathImg and x, all of the
onclick functions reference back to the same value, which is whatever
they were set to last.
Is there a way to solve this. Where am I doing mistake?

There is a thread here that will help with both questions:

Subject: function syntax question
<URL;
http://groups.google.com.au/group/c...unction+closure&rnum=1&hl=en#a50caf593c683e27
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top