-1

When I click on the li I got a new li created. However clicking I want the same event on the new list items so I used:

$('ul').on( 'click', $this, function(){

But now the content is duplicated!

<ul>
  <li>1</li>
  <li>2</li>
</ul>

JS:

(function(){
    $('li').each(function(){
        var $this = $(this);
        $('ul').on( 'click', $this, function(){
            $('ul').append('<li>new</li>');
        });
    });
})(jQuery)

http://jsfiddle.net/24cnwmqv/1/

I just want when you click on the existing or new list items you got 1 new created list item. Thank you.

Peter B
  • 18,964
  • 5
  • 26
  • 60
mamaia84x
  • 3
  • 1

2 Answers2

0

Simply use:

$('ul').on( 'click', 'li', function(){
  $('ul').append('<li>new</li>');
});

Here's the updated fiddle.

Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
0

The problem is because you're duplicating click event handlers in the each loop - remove that. Then use li as the selector instead of the $li reference:

(function() {
  $('ul').on('click', 'li', function() {
    $('ul').append('<li>new</li>');
    
    var index = $(this).index();
    console.log(index);
  });
})(jQuery)
li {
  background: #ccc;
  width: 50px;
  padding: 5px 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
</ul>

You may also want to consider changing the logic to only append to the parent ul instead of all in the current DOM:

$(this).closest('ul').append('<li>new</li>');
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303