jQuery Resolves the Method of Not Executing Original Events after Adding Elements

  • 2021-12-09 08:13:28
  • OfStack

Let's look at my error code first

html:


        <table border="1" id="best">
			<tr>
				<td>
					<button class="change"> Modify </button>
				</td>				
			</tr>
			<tr>
				<td>
					<button class="del"> Delete </button>
				</td>				
			</tr>
			<tr class="last"><td><button class="add"> Add </button></td></tr>
		</table>

js:


$(".add").click(function(){
		var newYuansu = $("<tr><td><button class='del'> Delete </button></td></tr>");
		$(".last").before(newYuansu);
})
$(".del").click(function(){
        $(this).parents("tr").remove();
})

At this time, using jQuery to add a new element, the new element will not execute the 1 part of the original event function

The blogger is a student and only studied one method:


$("#best").on("click",".del",function(){
		$(this).parents("tr").remove();
})

If the original click event is written like this, it can be used in newly added elements, which is very easy to use ~

Additional:

1. For those under jquery 1.3 (excluding jquery 1.3), it's time to update your jquery version.

Because there is no solution, no solution, no solution, no solution, no solution

2. If jquery version is between 1.3 and 1.8, js/jq dynamically added elements trigger the solution of binding events (on event is not recommended, because on event is not supported below version 1.6, and an error will be reported)

Bind live events (live events are only supported under jquery 1.9 and are not supported in higher versions).


$(".del").live("click",function(){ ///jquery 1.9( Not included 1.9) You can 

               alert(' Here are the events added by dynamic elements ');

           })

3. on is recommended

If the jquery version is 1.9 or higher, the live delegate event is removed and implemented via on. Solution of js/jq Dynamic Added Element Triggering Binding Event

Note: If a page has both a lower version of jq (1.3-1.8) and a higher version of jq (above jquery 1.9), the live delegate event will be removed by the higher version, resulting in an error when the live event is used even though there are jquery versions between 1.3-1.8.


Related articles: