0

I click on "My link1", i have the alert "I clicked on" -> OK
I click on button "Add line", it adds my link 2 -> OK
I click on "My link2" just added, nothing happens. -> KO

Any help is welcome.

This is my code

<ul style="list-style-type: none;padding-left: 0px;" id="listitems">
  <li ><a href="#" id="mylink">my link 1</a></li>
</ul>
<button onclick="addrecepitem();" id="btnrecepajouter">Add line</button>

<script>
function addrecepitem(){
document.getElementById('listitems').innerHTML += '<li id="mylink">my link 2</li>';
}

$('#mylink').click(function(){
alert('I clicked on ');
}

</script>

Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
Alexis
  • 21
  • 4

2 Answers2

1

The event handler is set in the beginning when the element is not made yet.

Set the event handler on the window like this:

$('window').on('click', '.link', function(e) {
     alert('I clicked on', e.Target);
});

Anyhow setting the same id for different elements is bad practice. Try to use classes instead.

Wimanicesir
  • 3,428
  • 2
  • 9
  • 23
0

you have made some basic and conceptual mistakes in your code.

  1. id should be identical so you should not use duplicate ids.
  2. you are using the click event on a particular id. So this event only triggers when your click in that element. I have made some updates based on your requirements. check now

var counter = 2;
function addrecepitem(){
document.getElementById('listitems').innerHTML += '<li> <a href="#">my link '+ counter++ +'</li>';
}


$( "#listitems" ).on( "click", "li", function() {
  console.log( $( this ).text() );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul style="list-style-type: none;padding-left: 0px;" id="listitems">
  <li ><a href="#">my link 1</a></li>
</ul>
<button onclick="addrecepitem();" id="btnrecepajouter">Add line</button>
king neo
  • 2,141
  • 1
  • 17
  • 26