Good evening. There is such a code (simplified)

<div data-user-email="<?=$users['email']?>" data-event-id="<?=$event['id']?>" class="event-div"> <span class="my_btn delete-event" style="background-color: red;">Удалить</span> </div> 

Output this block in a cycle, so the data-user-email and data-event-id values ​​are different. How to get the data attribute value when you click on the delete-event button in the current block.

    3 answers 3

     $(function(){ $('.delete-event').click(function(e){ var parent = $(this).parent('.event-div'); $("#result").html("Email: "+parent.data('user-email')+"; Event: "+parent.data('event-id')); return false; }); }); 

    https://jsfiddle.net/bookin/dehgyo39/

      Through the native method of the Node object in vanilla JS.

       $(".delete-event").on("click", function() { var id = $(this).dataset.eventId; var email = $(this).dataset.userEmail; }); 
      • You forgot that you need to take datasets not from the object you clicked on, but from your ancestor - Alexey Shimansky
      • @ Alexey Shimansky Apparently did not notice this in the question. I apologize to the author. - smellyshovel

      closest - for each of the selected elements, closest () will search for the closest matching element from among the following: the selected element itself, its parent, its progenitor, and so on, until the beginning of the DOM tree

       $('.delete-event').on('click', function() { var innerBlock = $(this).closest('.event-div'); console.log('email: ' + $(innerBlock).data().userEmail + ', eventId: ' + $(innerBlock).data().eventId); /* для dataset var innerBlock = $(this).closest('.event-div')[0]; // var innerBlock = this.closest('.event-div'); console.log('email: ' + innerBlock.dataset.userEmail + ', eventId: ' + innerBlock.dataset.eventId); */ }); 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-user-email="userEmail666@mail.ru" data-event-id="eventId666" class="event-div"> <span class="my_btn delete-event" style="background-color: red;">Удалить 666</span> </div> <div data-user-email="userEmail333@mail.ru" data-event-id="eventId333" class="event-div"> <span class="my_btn delete-event" style="background-color: red;">Удалить 333</span> </div> <div data-user-email="userEmail999@mail.ru" data-event-id="eventId999" class="event-div"> <span class="my_btn delete-event" style="background-color: red;">Удалить 999</span> </div>