简体   繁体   English

回调 function 未定义,即使它在调用 javascript 之前已经定义

[英]Callback function not defined even though it has been defined right before calling in javascript

I am using for loop get all the data place in a div.我正在使用 for 循环获取 div 中的所有数据。 I have following code in javascript so far:到目前为止,我在 javascript 中有以下代码:

<script type="text/javascript">
function callback(){
    $.getScript("/frontend/vendor/jquery/jquery.min.js", function() {
      $('input').on('change', function(){
        var qty = $(this).attr('id');
        var price = $('#'+qty+'_price').attr('value');
        var subtotal = qty * price;
        $('#'+qty+'_total').html('&euro; '+subtotal);
      })
    });
  }

  function checkout(callback){
    let eventDate = JSON.parse(localStorage.getItem("events"));
    var unique = eventDate.filter(function(itm, i, eventDate) {
        return i == eventDate.indexOf(itm);
    });
    let items = [];
    for (var n = 0; n < unique.length; n++){
        var eventId = unique[n];
        $.ajax({
            "url":"/get_my_product/"+ eventId,
            "type":"GET",
            "dataType":"json",
            "contentType":"application/json",
            success:function(response){
              let party = 'Party name';
              let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>"+party+"</a></h5></td><td class='product-col'><h5 class='product-title'><a>"+response.date+"</a></h5></td><td value='"+response.price+"' id='"+n+"_price'>&euro; "+response.price+"</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty'  id='"+n+"' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='"+n+"_total'>&euro; "+response.price+"</td></tr>";
              $('#data').append(html);
            }
        })

    }
    callback && callback();
  }
  checkout();    
</script>

When I am trying to call the function after the loop completion it does not work.当我在循环完成后尝试调用 function 时,它不起作用。 What is wrong here?这里有什么问题?

Change改变

function checkout(callback){

to

function checkout() {

I think the argument callback to the function checkout "shadows" the previously defined callback function.我认为 function checkout的参数callback “遮蔽”了先前定义的callback function。 Then, when you call the function checkout you are passing nothing to the function, and callback will be undefined .然后,当您调用 function checkout时,您不会向 function 传递任何内容,并且callback将是undefined

Or, in the last line, pass the function as an argument:或者,在最后一行,将 function 作为参数传递:

checkout(callback);

Makes no sense to add another version of jQuery to add events.添加另一个版本的 jQuery 以添加事件是没有意义的。 You are not passing the callback to the method so it is always going to be undefined.您没有将回调传递给该方法,因此它始终是未定义的。 And you are not waiting for the Ajax calls to complete before calling the callback.在调用回调之前,您无需等待 Ajax 调用完成。

// No reason for loading the JQuery version here
function addMyEvents() {
  $('input').on('change', function() {
    var qty = $(this).attr('id');
    var price = $('#' + qty + '_price').attr('value');
    var subtotal = qty * price;
    $('#' + qty + '_total').html('&euro; ' + subtotal);
  })
}

function checkout(callback) {
  // hold the ajax calls
  const myAjaxCalls = []
  let eventDate = JSON.parse(localStorage.getItem("events"));
  var unique = eventDate.filter(function(itm, i, eventDate) {
    return i == eventDate.indexOf(itm);
  });
  let items = [];
  for (var n = 0; n < unique.length; n++) {
    var eventId = unique[n];
    // push the ajax calls to an array
    myAjaxCalls.push($.ajax({
      "url": "/get_my_product/" + eventId,
      "type": "GET",
      "dataType": "json",
      "contentType": "application/json",
      success: function(response) {
        let party = 'Party name';
        let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>&euro; " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty'  id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>&euro; " + response.price + "</td></tr>";
        $('#data').append(html);
      }
    }))

  }
  // if we have a callback
  if (callback) {
    // wait for all the ajax calls to be done
    $.when.apply($, myAjaxCalls).done(callback)
  }
}
// pass the function to the method.
checkout(addMyEvents);

Now the best part is you do not even need to worry about the callback to bind events.现在最好的部分是您甚至不需要担心绑定事件的回调。 You can just use event delegation and it would work.您可以只使用事件委托,它会起作用。 This way whenever an input is added to the page, it will be picked up.这样,每当将输入添加到页面时,它就会被拾取。

$(document).on('change', 'input', function() {
    var qty = $(this).attr('id');
    var price = $('#' + qty + '_price').attr('value');
    var subtotal = qty * price;
    $('#' + qty + '_total').html('&euro; ' + subtotal);
})

function checkout() {
  let eventDate = JSON.parse(localStorage.getItem("events"));
  var unique = eventDate.filter(function(itm, i, eventDate) {
    return i == eventDate.indexOf(itm);
  });
  let items = [];
  for (var n = 0; n < unique.length; n++) {
    var eventId = unique[n];
    $.ajax({
      "url": "/get_my_product/" + eventId,
      "type": "GET",
      "dataType": "json",
      "contentType": "application/json",
      success: function(response) {
        let party = 'Party name';
        let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>&euro; " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty'  id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>&euro; " + response.price + "</td></tr>";
        $('#data').append(html);
      }
    })
  }
}

checkout();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM