jquery dynamically add element event

When developing the project, the Change event of the DropDownList of the selection box sometimes needs to be cascaded in multiple levels to dynamically generate the Select element, but the Change event of the Select element cannot be triggered at this time, which is very distressing.  

There are two methods used in the project. One is to write the event into the partial view when reclaiming the element, but this method works well, but when I make another view, it never works, very irritable. I tried the methods of bind live and on, but the solution was not very good. Finally, the following method was adopted. I hope that there are similar children's shoes to find the answer here.  

 

One way is to register the following event in $(document).ready(init) of document, and then re-introduce the event when creating a new element.

$("select[name='Collection']").change(function () {  
  
            var selectedTypeID = $(this).val();  
            $.ajax({  
                url: '@Url.Content("/Products/GetSkuView")',  
                type: "POST",  
                dataType: "html",  
                data: { Collection: selectedTypeID },  
                success: function (data) {  
                    //$('#DDLSpecies').html(data);  
                    $("#SKU").prop('outerHTML', data);  
                },  
                error: function (XMLHTTPRequest, textStatus, errorThrown) {  
                    $.AlertException(XMLHttpRequest, errorThrown);  
                }  
            });  
        });  

The second way is to directly write the following way:

$(document).on('change', '#SKU', function () {  
       //alert('hhhhhh');  
       var selectedTypeID = $(this).val();  
       $.ajax({  
           url: '@Url.Content("/Products/GetSpeciesView")',  
           type: "POST",  
           dataType: "html",  
           data: { SKU: selectedTypeID },  
           success: function (data) {  
               //$('#Species').html(data);  
               //alert(data);  
               $("#Species").prop('outerHTML', data);  
           },  
           error: function (XMLHTTPRequest, textStatus, errorThrown) {  
               $.AlertException(XMLHttpRequest, errorThrown);  
           }  
       });  
   });  

I have tried methods such as $('#SKU').on('change',...), but it didn't work. Maybe it was written wrong there. I solved it by using the second method. I record it here, I hope it will help you a little. .

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327079382&siteId=291194637