0

I was hoping to keep cross-browser compatibility and afaik this is the only issue so far.

.setAttribute("onclick", "return showRapidText("+itemnum+");"); 

This works PERFECT but I'd like to make it IE compatible by putting it in this syntax

.onclick = new Function("fnDisplay_Computers('" + alines[i] + "')");

so... I tried

.onclick = new Function("showRapidText('" + itemnum + "')");

and

.onclick = new Function("return showRapidText('" + itemnum + "')");

and about 40 other ways but nothing works

Max
  • 1
  • Thank you for both your answers and your right that I was trying to do this in a loop so that first answer didn't workout for my problem. What I ended up doing that works like a charm is this. xxx.setAttribute("itemnum",itemnum); xxx.onclick = function() { return showRapidText(this.getAttribute("itemnum")); }; This answer was provided by a very nice and brilliant member of codingforums by the name of Old Pendant. – Max Apr 26 '10 at 21:43

2 Answers2

3
element.onclick = function() {
    return showRapidText(itemnum);
};
James
  • 109,676
  • 31
  • 162
  • 175
1

+1 J-P's answer: function literals are massively better than strings. Hacking together code in strings is a horror you should avoid at all costs. Also setAttribute should almost never be used in an HTMLDocument due to IE compatibility (and because DOM Level 1 HTML properties are more readable anyway).

One potential trap though: if you are doing this in a loop, which it looks as if you are, you won't get the behaviour you want, due to the closure loop problem. You can solve this with another closure:

for (var i= 0; i<alines.length; i++) {
    elements[i].onclick= function(i) {
        return function() {
            fnDisplay_Computers(alines[i]);
        };
    }(i);
}

or more cleanly by using the ECMAScript Fifth Edition feature Function#bind:

for (var i= 0; i<alines.length; i++) {
    elements[i].onclick= fnDisplay_Computers.bind(null, alines[i]);
}

Adding Function#bind to browsers that don't yet support it.

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834