简体   繁体   中英

how to let js know about newly created html element

i am creating new html element with js.

$('#write_comment').on('click',function(){
  $(this).html('<textarea> </textarea><button onclick="test()">save</button>');
});

function test(){
 alert('testme');
}

but after these textarea and button were created, if i click on save , nothing happens.

is there any jquery function where i can say. (newly_created_element).find(js_function) ?

that or something with same functionality would be nice to have.

please help.

$('#write_comment').on('click',function(){
  $(this).html('<textarea> </textarea><button id="test">save</button>');
});

$('body').delegate('#test','click',function(){
 alert('testme');
});

Using class

$('#write_comment').on('click',function(){
      $(this).html('<textarea> </textarea><button class="test">save</button>');
    });

    $('body').delegate('.test','click',function(){
     alert('testme');
    });

Create the button seperately:

$('#write_comment').on('click',function(){
  var myButton = $('<button>save</button>').click(function() {
    test();
  });
  $(this).html('<textarea></textarea>').append(myButton);
});
$('#write_comment').on('click',function(){
  $(this).html('<textarea> </textarea><button class="NewlyAdded">save</button>');
});

$(document).on behaves like .live() or delegate() in many ways. And will work for elements that are added later .

$(document).on('click','#write_comment button.newlyAdded',function()
{
  alert('testme');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM