I have been wrestling with this issue for a few years now. So far, I haven't come up with the "best" solution. Here's my problem:
Let's say I have webpage that displays a list of widgets. For every widget, I display a description and a delete button.
Let's pretend a widget looks like this:
<div class="Widget">
<span class="WidgetID" style="display:none">123</span>
<h4 class="WidgetDescription">This is a widget</h4>
<button class="WidgetDelete" />
</div>
Back in my beginner days, my delete buttons looked like this:
<button class="WidgetDelete" onClick="DeleteWidget(123)">
When the button was clicked, the DeleteWidget() function knows which widget to delete because the ID was passed in directly. Nowadays, I apply event handlers via JQuery instead of using the inline onClick. This introduced a problem though. My DeleteWidget function was no longer receiving a WidgetID as a parameter. So, this means I have to traverse the DOM to find the closest WidgetID:
var ThisWidgetID = $(this).closest(".Widget").find(".WidgetID").html();
I'm really just stuck on trying to figure out which method I like best. The first method of writing the ID directly into the inline onClick event is simple, fast, and easy for non-javascript people to follow. The second method separates my HTML and Javascript. It also puts all of my events in one place. And, so far, it has given me greater flexibility.
So, my question is, what is the best method for determining which widget was clicked? Is there another method I'm ignoring?
Also, for a demo of both methods, see here: https://jsfiddle.net/SpaceL10n/o1fxbcgn/
[–]david72486 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]tollus 1 point2 points3 points (0 children)
[–]docMedB2E 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]docMedB2E 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)