开发者

jquery append to already appended div

开发者 https://www.devze.com 2023-01-14 09:18 出处:网络
Is it possible to append something to a div that was already appended? I tried but nothing happens.. (I\'m not using linebreaks in the actual js)

Is it possible to append something to a div that was already appended? I tried but nothing happens.. (I'm not using linebreaks in the actual js)

$(document).ready(function() {

    $('.add_text_input').click(function() {
        $('li').append('<div class="input_label">Untitled</div>\
                        <div class="edit_label"></div>\
                        <input type="text" name="untitled" /><br />');
    });

    $('.input_label').click(function() {    
        var input_label = $(this).html();   
        $(this).hide();
        $('.edit_label').append('<input type="text" name="untitled" value="' + input_label + '"/><br />');
    });

});

The js is for creating text inputs and editing their labels. Whe开发者_运维技巧n clicking on the "input_label" div, it should hide using hide() and append a text input with the default "untitled" value in the "edit_label" div. It works if the divs already exist but I need to make it work via append.

Does anyone have any ideas please?


You just need to use a .live() handler here, like this:

$('.input_label').live('click', function() {
  var input_label = $(this).html();   
  $(this).hide().next('.edit_label')
    .append('<input type="text" name="untitled" value="' + input_label + '"/><br />');
}); 

This will work on elements regardless of when they're created, since it works off event bubbling, it'll work on any element's click event that matches the .input_label selector.

Currently with .click() it's finding all the elements that exist at document.ready time and binding to those elements, not to the selector, so it won't work for dynamically added elements.

0

精彩评论

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