javascript – onclick doesn’t work properly after append

بدون دیدگاه



In my code, on fly I am creating unordered list items. Each of which contains a text and an anchor tag (red cross sign). Now what I want is that on clicking the anchor tag it prints the child number of the list item it’s in. I want this without reloading the page.

 if (status === 'success') {
     const i = document.createElement("i");
     i.classList.add("fa");
     i.classList.add("fa-times");
     i.classList.add('red-cross');

     const a = document.createElement("a");
     a.classList.add("ml-4");
     a.append(i);

     const t = document.createTextNode(txt)

     const newItem = document.createElement("li");
     newItem.append(t);
     newItem.append(a);

     $("ul#"+list).append(newItem).on('click', 'li a', function() {
         const cnt =  $("ul#"+list).children().length;
         console.log(cnt);
     }); }

View:
Unordered list of items with text and cross sign

Expected output:
On clicking i’th cross sign output shoud be i.

Current output:
The output is always 6 regardless which number cross I click.



لینک منبع

  • نویسنده
    A-brand
  • تعداد بازدید
    20 views
0دیدگاه فرستاده شده است.
شما هم دیدگاه خود را بنویسید