jquery - Change Div Content with JavaScript, onmouseover and onmouseout? -
i have following code:
window.onload = function createdivs() { for(var = 1;i<29;i++) { var div = document.createelement("div"); var body = document.getelementsbytagname("body")[0]; var n1 = document.createtextnode("cell " + i); var n2 = document.createtextnode(i + " cell"); div.style.width = "100px"; div.style.height = "100px"; div.style.border = "1px solid red"; div.style.cssfloat = "left"; div.style.margin = "1px" div.classname = i; body.appendchild(div); } div.onmouseover = function() { this.appendchild(n1); }, div.onmouseout = function() { this.appendchild(n2); } }
what want acheive
- on mouseover of each div, div should have text of cell 1, cell 2, ..... upto cel 28. getting cell 28 on hover each cell.
2. want achieve onmouseout, cell should have "1 cell
" text, not working.
any appreciated.
your problem coming closure on n1
, n2
. simplest solution following.
from this:
div.onmouseover = function() { this.appendchild(n1); }
to this:
div.onmouseover = (function(text) { return function () { this.innerhtml = text; } }(n1.textcontent));
this way using copy of text node (by using parameter function) rather closure later on.
update
just read second part of question, should work:
div.onmouseover = (function(text) { return function() { this.innerhtml = text; }; }("cell " + i)); div.onmouseout = (function(text) { return function() { this.innerhtml = text; }; }(i + " cell"));
using text nodes
function createdivs() { for(var = 1;i<29;i++) { var div = document.createelement("div"); var body = document.getelementsbytagname("body")[0]; div.style.width = "100px"; div.style.height = "100px"; div.style.border = "1px solid red"; div.style.cssfloat = "left"; div.style.margin = "1px" div.classname = i; var n1 = document.createtextnode("cell " + i); var n2 = document.createtextnode(i + " cell"); body.appendchild(div); div.onmouseover = (function(n_text1, n_text2) { return function() { if (n_text2.parentnode == this) { this.removechild(n_text2); } this.appendchild(n_text1); }; }(n1, n2)); div.onmouseout = (function(n_text1, n_text2) { return function() { if (n_text1.parentnode == this) { this.removechild(n_text1); } this.appendchild(n_text2); }; }(n1, n2)); } }
fiddle here: http://jsfiddle.net/mk5e5/
Comments
Post a Comment