문제

My question is, why isn't the click event on the third div triggered anymore, after i've detached the elements and appended them back? The events aren't preserved.

var test = (function($, undef) {
    var t = {};
    t.test = function(){
        var container = $('<div/>').appendTo('body');           
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);         
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);         
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text',
            'click' :   function(){
                console.log("ahoy");
            }
        }).appendTo(container);         
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);         
        var content = container.html();
        var detachedContent = $(content).detach();
        container.empty();          
        //setTimeout(function(){
            container.append(detachedContent);
        //}, 2000);         
    };      
    return t;
})(jQuery); 
test.test();

example: http://jsfiddle.net/sCJfc/

도움이 되었습니까?

해결책

detach() is not to blame here.

You're performing a copy of the container element's inner markup, and you're detaching the elements created from that copy. These elements are not part of the DOM to begin with, and will indeed not have any handler registered on them.

Try writing:

var detachedContent = container.children().detach();

Instead of:

var content = container.html();
var detachedContent = $(content).detach();

다른 팁

Try cloning the child elements, removing them and then adding them back using the clone.

var detachedContent = $(container).children().clone(true);
console.log(detachedContent);
container.empty();

container.append(detachedContent);

Working Example: http://jsfiddle.net/sCJfc/2/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top