jQuery global variable problem

前端 未结 6 819
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 10:58
var id = $(this).children().html();  // id is 5
$.ajax({
   url: \'ajax.php?id=\' + id,
   success: function(data) {
      id = data;   // id is 1
   }
});
if(id == 1){          


        
6条回答
  •  心在旅途
    2021-01-22 11:15

    Refactoring the code like this would work:

    function by_id() {
     if(id == 1) {   
       ... do something ...
     }
    }
    
    var id = $(this).children().html();
    $.ajax({
       url: 'ajax.php?id=' + id,
       success: function(data) {
          id = data;
          by_id();  // call on successful ajax load
       }
    });
    

    The advantage of wrapping your id logic in a function allows you to call it anywhere - be it at the end of an AJAX request, at page load, on a button press, etc.

提交回复
热议问题