javascript - trouble updating multiple anchors aysc with jquery -


so have these links in html this

<a href="#ajax" class="invlink" competition_id="532">gen invoice</a> <a href="#ajax" class="invlink" competition_id="534">gen invoice</a> <a href="#ajax" class="invlink" competition_id="535">gen invoice</a> 

then wrote javascript binds click event , want submit ajax request, , replace anchor returned text. if have clicked on multiple links several running asychronously, doesn't update anchors returned text, last anchor clicked on.

i guessing anchor variable being overwritten each time run, how structure code each time click event triggered, updates correct anchor on completion?

here javascript

<script type="text/javascript">      $(document).ready(function() {         // bind geninvoice function invlink's         $('.invlink').bind('click', geninvoice);     });       function geninvoice() {          // stop double clicks         anchor = $(this);         anchor.unbind('click');          competition_id = $(this).attr('competition_id');          $.ajax({             type: "post",             url: "<?php echo url::site('manage/ajax/geninvoice'); ?>/"+competition_id,             datatype: "json",             beforesend: function() {                 anchor.addclass("loading");             },             success: function(response, textstatus) {                 anchor.replacewith(response.invoice_number);             },             error: function(response) {                 alert("unknown error occurred");                 anchor.bind('click', geninvoice); // rebind if error occurs             },             complete: function() {                 anchor.removeclass("loading");             }         });     }  </script> 

yeah, problem anchor variable written being 'hoisted' global scope. see this jsfiddle simplified example.

you can fix this, putting var in front of variable, scope limited function:

function geninvoice() {      // stop double clicks     var anchor = $(this); //<-- put var here 

you can see fix @ updated version of above fiddle

note, scoping within functions. x variable in following example hoisted top of global scope though has been declared var:

var = 1; var b = 1;  if (a === b){    var x = 0; }  alert(x); //alerts '0' 

the advantages of scoping within functions on of reasons see following convention around jquery plugins:

(function($){     //plugin code     //all variables local invoked anonymous function })(jquery); 

see @ this jsfiddle


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -