The issue with your current code is that you attach the event when the element has the attribute. The fact you change the attribute afterwards does not remove that event handler, so it is always called.
There are several ways to fix this.
The first is to use a delegated event handler, which will always account for the current attribute value:
$(document).on('click', 'a[data-spinner="true"]', function() {
$(this).attr("data-spinner", false);
alert("clicked");
});
Another method is to check the state of the attribute within the click handler itself:
$("a[data-spinner]").click(function() {
if ($(this).data('spinner')) {
$(this).data('spinner', false)
alert("clicked");
});
});
Note that this method allows you to use the data()
method which is considered better practice.
You could also remove the event handler using off()
on the first click, or just use one()
to attach the event - depending on the other logic in the page which sets the data
attributes' value.