mardi 5 juillet 2016

Do not bind an event handler if has been already bound


I am calling some forms using ajax, and then binding an event handler for every button. The problem is... when I call a new form using ajax the event handler is called again for the new elements and then it's added twice for the previous elements. How can I detect if an event handler is already on an element and not bind it again?

function x(){
    $("input:button").click(function(){
        alert('is this called once?');
    });
}

<input type='button' value='Disable me' />
<input type='button' value='Disable me' />

function x(){
    $("input:button").click(function(){
        alert('is this called once?');
    });
}

// calling event twice simulating an ajax calling:
x();
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='button' value='Disable me' />
<input type='button' value='Disable me' />

Aucun commentaire:

Enregistrer un commentaire