javascript - Why does my jquery delegated click fire multiple times? -
i copying element , adding a list of elements. first, sonme html using ajax call:
var setbuttonclick = function (url, btn) { $.ajax(url, $('form').serialize(), 'html').then(function (data) { $(btn).parent().find(sel.addlistitem).on('click', function () { addlistitem(data, this, btn); }); addlistitem(data, btn, btn); }); }
addlistitem looks this.
var addlistitem = function (data, context, btn) { var $template = $(data); // stuff not related removed brevity $(btn).before($template); }
i have remove function using delegate:
$(sel.editablelist).delegate(sel.removelistitem, 'click', function () { // fires once every element sel.removelistitem selector }
i need click event fire once clicked element only. can basic version of delegate
working inserting content this:
$( "body" ).delegate( "p", "click", function() { $( ).after( "<p>another paragraph!</p>" ); });
therefore, i'm thinking may because i'm inserting copy of element or same element i'm adding on , over? i've tried use clone
create new element before inserting like:
var $template = $(data).clone();
can show me going wrong please?
thanks
the problem every time ajax called attach click event handler elements. gets called repeatedly, because add elements existed , had handler attached.
the solution problem detach attached handlers off()
function.
var setbuttonclick = function (url, btn) { $.ajax(url, $('form').serialize(), 'html').then(function (data) { $(btn).parent().find(sel.addlistitem) .off('click') .on('click', function () { addlistitem(data, this, btn); }); addlistitem(data, btn, btn); }); }
#
in future may want attach different click event handlers or may want turn off specific handlers, use namespaces.
$(elem).on('event.namespace', function(){}); $(elem).off('event.namespace');
that way have multiple click event handlers on 1 element. code if have more 1 click event handlers
var setbuttonclick = function (url, btn) { $.ajax(url, $('form').serialize(), 'html').then(function (data) { $(btn).parent().find(sel.addlistitem) .off('click.additem') .on('click.additem', function () { addlistitem(data, this, btn); }); addlistitem(data, btn, btn); }); }
#
and here's example.
$('.btn').on('click.ns1', function(){ alert('hey'); }); $('.btn').on('click.ns2', function(){ alert('how doin?'); }); // comment me out see difference $('.btn').off('click.ns2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn">click me</button>
Comments
Post a Comment