why i can't use attachEvent with innerHTML;

S

SkyZhao

if i use AttachEvent like this,it can't work;
eg:

var img = document.createElement("img");
img.attachEvent("onclick",alert("test"));
var div = document.createElement("div");
div.appendChild(img); //can't work;
div.innerHTML="<-click this";


but i use attachEvent like this,it work;
eg:

var img = document.createElement("img");
img.attachEvent("onclick",alert("test"));
var text = document.createElement("span");
text.innerHTML="<-click this";
var div = documet.createElement("div");

div.appendChild(img); //can work
div.appendChild(text);
 
P

Peter Michaux

if i use AttachEvent like this,it can't work;
eg:

var img = document.createElement("img");
img.attachEvent("onclick",alert("test"));
var div = document.createElement("div");
div.appendChild(img); //can't work;
div.innerHTML="<-click this";

but i use attachEvent like this,it work;
eg:

var img = document.createElement("img");
img.attachEvent("onclick",alert("test"));
var text = document.createElement("span");
text.innerHTML="<-click this";
var div = documet.createElement("div");

div.appendChild(img); //can work
div.appendChild(text);

Was there a problem with the answer I supplied before?

<URL: http://groups.google.com/group/comp.lang.javascript/msg/de4303743575ead4>

Peter
 
P

Peter Michaux

if i use AttachEvent like this,it can't work;
eg:

var img = document.createElement("img");
img.attachEvent("onclick",alert("test"));
var div = document.createElement("div");
div.appendChild(img); //can't work;
div.innerHTML="<-click this";

The above line removes the image from the div. InnerHTML removes all
other children from the element.

replace this
div.innerHTML="<-click this";

with

div.appendChild(document.createTextNode('<--click this'));

You should be able to see both the image and the text this way.

Peter
 
S

SkyZhao

The above line removes the image from the div. InnerHTML removes all
other children from the element.

replace this


with

div.appendChild(document.createTextNode('<--click this'));

You should be able to see both the image and the text this way.

Peter

can i use this
div.innerHTML+="<--click this" ?
 
P

Peter Michaux

can i use this
div.innerHTML+="<--click this" ?

You can but I probably wouldn't since this requires conversion of dom
to string and back to dom for the image. That is unnecessary.

Peter
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top