-2

when i click button append elements to body and when i click on the appended button(hide button) not work. It does not work well.please help me for this problem.

function func_add(){
  $('body').append('<div class="test"><button id="hide-btn">hide</button><div id="red"></div></div>');
}

$('#btn').click(function(){
  func_add();
});

$('#hide-btn').click(function(){
 $('#red').hide();
});
#red{
  background:red;
  width:100px;
  height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
  <button id="btn">click me</button>
</body>
</html>
ks1313
  • 56
  • 7

1 Answers1

2

This is because $('#hide-btn') doesn't exists when you are adding click event listener. You should add click listener after adding button or use this:

$('body').on('click', '#hide-btn', function () {
    $('#red').hide();
});
Gaiozz
  • 111
  • 3