开发者

Clone a node using JavaScript DOM

I want to create a clone for below code using JavaScript DOM:

var summaryDiv = __createElement("div","sDiv","sDiv"+j);
        summaryDiv.onmouseover = function() {this.setAttribute("style","text-decoration:underline;cursor:pointer;");}
        summaryDiv.onmouseout = function() {this.setAttribute("style","text-de开发者_如何学JAVAcoration:none;");}
        if(browser.isIE) {
            summaryDiv.onclick = new Function("__fc.show_tooltip("+j+",'view_month')");
    } else {
            summaryDiv.setAttribute("onclick", "__fc.show_tooltip("+j+",'view_month',event)");
        }
   someobj.appendChild(summaryDiv);

I'm using obj = summaryDiv.cloneNode(true) which is creating a node, but the onclick event is not getting fired in the case of Internet Explorer. Can anybody help me over it?


this.setAttribute("style","text-decoration:underline

Don't use setAttribute, it won't work in IE<8 for many cases (including this one) and the HTML/CSS-DOM properties are more readable: this.style.textDecoration= 'underline';.

(These days you may want to use a CSS :hover rule instead of JS hover-highlighting. It's only IE6 where arbitary-hover doesn't work; the last remaining IE6 users can often do without the shiniest stuff as long it it still works. They're probably used to seeing broken web sites by now...)

    if(browser.isIE) {
        summaryDiv.onclick = new Function("__fc.show_tooltip("+j+",'view_month')");
    } else {
        summaryDiv.setAttribute("onclick", "__fc.show_tooltip("+j+",'view_month',event)");
    }

No need for nasty old browser sniffing (avoid!) as the first of those will work in all browsers. However, creating a function from a string is really ugly. You can use a function literal instead:

summaryDiv.onclick= function() {
    __fc.show_tooltip(j, 'view_month');
};

However if you're doing this in a loop (over j?) you may be subject to the Closure Loop Problem. You can get around that with another closure, but ECMAScript Fifth Edition's Function#bind is cleaner:

summaryDiv.onclick= __fc.show_tooltip.bind(__fc, j, 'view_month');

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

but onclick event [on clone] is not getting fire in case of Internet Explorer.

Yeah, it's normal for event handlers not to get copied when cloning. (Actually, it's usually IE mistakenly cloning listeners added via attachEvent that's the problem, so that's the other way around.)

If you want to retain the event handling after cloning you'll have to do it manually:

newClone.onclick= oldNode.onclick;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜