Erprobung Probe Prüfung" /> Erprobung Probe Prüfung" /> Erprobung Probe Prüfung"/>

Click on span elements that is added after page loads

162 views Asked by At

I have a div. After a click on a word, the div gets some spans. The Code:

<div id="show-data">
  <span>Erprobung</span> 
  <span>Probe</span> 
  <span>Prüfung</span> 
  <span>Test</span>
</div>

My problem: I want to click on the new span-tags too, but it doesn't work for me. Here is my code:

$('$data-show').on('mouseover','span',function(){
    alert("Test");
});  
<div id="show-data"></div>

What is the solution to this issue? Thank you very much.

1

There are 1 answers

1
Kiran Shahi On BEST ANSWER

Use #show-data instead of $data-show and click() event instead of mouseover() event.

$('#show-data').on('click','span',function(){
  alert($(this).text());
});
    
var count = 0;
$('button').on('click', function(){
  count = count+1;
  $('#show-data').append('<span>Test'+count+'</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="show-data">
    <span>Erprobung</span> 
    <span>Probe</span> 
    <span>Prüfung</span> 
    <span>Test</span>
    </div>
    <button>Add Span</button>