Binding event loss method after dynamic addition of jQuery page elements non live

  • 2021-06-28 10:52:27
  • OfStack

Code 1: input box events bound in this way will be lost when jquery is bound after the add button


<input type="button" value="Add" name="test_but" />
<div id="test_div"><input name="test_input"/></div>
<script>
$('input[name=test_input]').change(function(){
alert($(this).val()) ;
});
$('input[name=test_but]').click(function(){
$('input[name=test_input]').clone().appendTo($('#test_div'));
});
</script> 

Code 2: Bind change event with jquery's live method, alert will not be lost, but it is possible to add input multiple times when you click add, or pop up a reminder box multiple times. It will be fine after refreshing the page, but it will be the same after many operations.


<input type="button" value="Add" name="test_but" />
<div id="test_div"><input name="test_input" onchange="alert_val(this)"/></div>
<script>
$('input[name=test_input]').live('change',function(){
alert($(this).val()) ;
});
$('input[name=test_but]').click(function(){
$('input[name=test_input]').clone().appendTo($('#test_div'));
});
</script> 

Code 3: Solution....


<input type="button" value="Add" name="test_but" />
<div id="test_div"><input name="test_input" onchange="alert_val(this)"/></div>
<script>
function alert_val(obj){
alert($(obj).val());
}
$('input[name=test_but]').click(function(){
$('input[name=test_input]').clone().appendTo($('#test_div'));
});
</script> 

Pass in the object itself through the js native onchange event, so that you can continue to write using the jquery syntax, without losing the binding event, and not because the live feature causes the event to execute multiple times.... Perfect!


Related articles: