This will bind a click event only once on the td
element
$(document).ready(function() {
$('#testin').one('click', function(){
alert('Hello there');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><span id="testin">Hello</span>
</td>
</tr>
</table>
EDIT
The main difference between my answer and Zakaria's reside in the fact the he can add more span later on (if you use class
instead of id
that is).
$('body').one('click', '#testin', function(){});
Binds all #testin
inside body
to a click
event.
$('#testin').one('click', function{});
Binds all #testin
that are already on the document
to a click
event.
EDIT 2
to answer your question:
It keeps showing the alert box. What is wrong with this code?
You haven't binded an event to the td
element, every time it is clicked it call a function name disconnectHandler()
.
function doSomething() {
alert('alerted')
}
function removeEvent() {
document.getElementById('doer').removeEventListener('click', doSomething);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="doer" onclick="doSomething()">Click me</p>
<p id="undoer" onclick="removeEvent()">Remove his event</p>
As you can see, the so-called event is part of his DOM. You are not removing the attribute, that is why it still call the function