Re: Events on dynamically generated elements in IE



On Apr 20, 5:49 pm, Harlan Messinger
<hmessinger.removet...@xxxxxxxxxxx> wrote:
Martin Honnen wrote:
Harlan Messinger wrote:

I'm using element.setAttribute("onblur", "alert('x')") .

Use
  element.onblur = function() { alert('x'); };
instead.
setAttribute is broken in IE versions before IE 8.

Thanks, Martin (and to the others who replied). I was about to whine
about the fact that what I'm starting with arbitrary attribute names and
values all stored as strings and that I need to apply dynamically to the
elements I'm generating, but then I remembered eval:

Forget eval.


/* IE event binding for dynamically created elements */
if (attr.indexOf("on") == 0 && document.attachEvent)

This logic makes no sense and you don't need to sniff for IE.

{
        eval("element." + attr + " = function() {" + this.attributes[attr] + "}");}

else
{
        element.setAttribute(attr, this.attributes[attr]);

}

element[attr] = new Function(this.attributes[attr]);

Of course, this is just eval in disguise. You might want to re-think
your design.


I used the attachEvent test after I wrote this morning after it was
mentioned in one of the responses; I decided to go your route on the
element.onXXXX strategy, but the attachEvent approach is still probably
good enough for figuring out that it's a browser calling for special
treatment.

Nonsense. It has nothing to do with the get/setAttribute methods.
And as is often the case, you don't need them.
.