Calling Onclick event after using outerHTML

this is the code:

$(".adauga_incasare").click(function(){
       var html = $(".incasari")[0].outerHTML;
       $(html).insertAfter($(".incasari").last());
    });

    $(".del_incasare").click(function(){
         alert("dsdasdasd");
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    			<div class="incasari">
    				<div class="data_incasare_container">
    					<label><b>Data</b></label>
    					<input class ="data_incasare" type="text" id="datepicker">
    					<label class ="data_incasare_hidden">12-06-2014</label>
    				</div>
    				<div class="suma_incasare_container" style="">
    					<label><b>Suma</b></label>
    					<input class="suma_incasare" type="text" maxlength="8" name="pret_unitar[]" alt=""> 
    					<label class ="suma_incasare_hidden">100</label>
    				</div>
    			    <div class="coscos" style="">
    			   	     <a class="stergereIncasare" href="javascript:void(0);"><i class="icon-trash"></i></a>
    			   	     <div style="clear:both;"></div>	
    			   	     <div class ="incasare_action">
    				   	     <input class="btn btn-success" type="button" style="margin-left:50px;width:80px;height:30px;float:left;" value="Salveaza"></input>
    				   	     <a href="javascript:void(0);" class="del_incasare delrow"></a>
    			   	 	 </div>
    			   	 	 <div style="clear:both;"></div>
    			    </div>
    			    <div style="clear:both;"></div>
    		    </div>
    
    		    <div style="clear:both;"></div>	
    			<a href="#" class="adauga_incasare">+ Adauga incasare noua</a>
    			<div class="toram">
    					<label style = 'cursor:default;'>Total incasat: <b>100 &euro;</b></label>
    					<label style = 'cursor:default;'>Total ramas: <b>1012 &euro;</b></label>
    			</div>		
    		</div>
Run codeHide result

externalHTML works fine, but when I "clone" the incasari class after that, when the onclick event does not work with the clone. I have a delete button. In the first class, “incasari” are in the works, but in the clone class they are not. Why?

+4
source share
2 answers

Use Event Delegation because your element is dynamically created after the click event has been assigned. For example, to delegate a document:

Demo

$(document).on("click", ".del_incasare", function(){
    alert("dsdasdasd");
});

, .del_incasare, , , .

+5

, , DOM, , DOM, , . , , . jQuery on.

$(document).on("click", ".del_incasare", function(){
    // do some cool stuff here.
});

, DOM .

0

Source: https://habr.com/ru/post/1546256/


All Articles