jQuery - Attach an event dynamically -
this question has answer here:
if create element class in jquery element wont include attached functions.
for example, in below code first of creating 2 different element in html , in (document.ready) assign change event class.
these 2 elements working properly. however, when click button, create new element has same class related event wont work element.
why happen? , how can attach events new element easily?
thanks in advance.
my code:
<body> <div class="main"> <input class="test" value="2" type="text"> <input class="test" value="3" type="text"> <input class="button" value="click" type="button"> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.test').change(function () { $('.main').append('<p>test</p>'); }); $('.button').click(function () { $('.main').append('<input class="test" value="x" type="text">'); }); }); </script>
$('.button').click(function () {});
only work on elements while code executed.
$('.button').on('click', function () {});
work on elements in document(even if added later)
Comments
Post a Comment