Hello. Got a question:

Suppose we have several links with data-attributes. For example:

<a href="#manual-modal" class="to_modal" data-desc="Descr #1" data-name="Name #1"></a> <a href="#manual-modal" class="to_modal" data-desc="Descr #2" data-name="Name #2"></a> <a href="#manual-modal" class="to_modal" data-desc="Descr #3" data-name="Name #3"></a> 

By clicking, I need to get the data from the data-attributes in order to display them in a modal window. But here's the problem: the id of the links is the same. How, then, to get the data from the link on which the click occurred?

Thanks for answers.

  • id у ссылок один и тот же - id or nonetheless class . If id is better then redo it, otherwise you won’t get any problems - Alexey Shimansky

1 answer 1

In the event handler, click this points to the DOM element on which the event occurred. In addition, as a parameter, the Event object is passed to the handler, which has a target property, which also points to the DOM element.

 $('.to_modal').click(function(event) { console.log($(this).data()) console.log($(event.target).data()) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#manual-modal" class="to_modal" data-desc="Descr #1" data-name="Name #1">1</a> <a href="#manual-modal" class="to_modal" data-desc="Descr #2" data-name="Name #2">2</a> <a href="#manual-modal" class="to_modal" data-desc="Descr #3" data-name="Name #3">3</a>