我的javascript不会在没有警报的情况下运行

My javascript doesn't run without alert

本文关键字:情况下 运行 有警 javascript 我的      更新时间:2023-09-26

我的代码块有问题,本节根据用户在上一步中选择的内容以及从 api 脚本中的数据库中提取的数据来创建巧克力盒。问题是,如果没有警报("嗨"),它就无法工作。如果我把它拿出来,它只会创建一个空框,而不会在其中放置口味,使用createFlavorArray函数插入风味。

var product = new Array();
var price = new Array();
var size = new Array();
$(function () {
      $.ajax({
        type: 'POST',
        url: 'phpscripts/api.php',      
        data: "",
        dataType: 'json',    
          success: function(rows)        
        {
        count = 0;
          for (var i in rows)
          {
            var row = rows[i];          
              product[count] = row[0];
              price[count] = row[1];
              size[count] = row[2];
              count++;
          }
        } 
      });
    });
//b = box
//o = option that is inside the box
//nextBoxId is the box id
//nextFlavorId is the option or flavor id
var nextBoxId = 1;
var nextFlavorId = 1;
var orderCap = 0;
var subTotal = 0;
var numOfChocolates = 0;
var numOfBoxes = 0;
$(document).ready(function(){
    while (halfPoundBoxes > 0) {
            $("#boxes").append('<div id="b'+nextBoxId+'"></div>');
            $('#b'+nextBoxId).addClass('div-table-selection');
            $('#b'+nextBoxId).append($('#minusBox').clone().attr('id', "m"+nextBoxId));
            $('#b'+nextBoxId).append('<div style="display:table-row"></div>');
            //call the function to loop through and create the number of flavor options needed
            var x = 0;
            alert('hi');
            while(x < product.length){
                if ('1/2lb Box' == product[x]) {
                    createFlavorArray(size[x], nextBoxId);
                    subTotal += price[x] * 1;
                    $('#b'+nextBoxId).attr('title', product[x]);
                }
                x++;
            }
            //clone the delete box button and make it visible
            $('#m'+nextBoxId).show(500);
            $('#b'+nextBoxId).append("<br />");
            if (orderCap == 0) {
            $('#boxes').append('<div id="msg"><p>If you wish to add another box to your order select the size and click +1 Box.</p></div>');
            }
            $("#m"+nextBoxId).click(function() {
                    $(this).parent().remove();
                orderCap--;
                //if they're ordering zero boxes hide the order button
                //remove total price
                //remove the message
                if (orderCap == 0)
                {
                    document.getElementById('orderBtn').style.display = "none";
                    $("#msg").remove();
                    $("#totalPrice").empty();
                }
                if (orderCap < 10)
                {
                    $("#cap").remove();
                    $("#addBox").show(500);
                }
                var y = 0;
                while (y < product.length) {
                    if ('1/2lb Box' == product[y]) {
                    subTotal -= price[y] * 1;
                    numOfChocolates -= size[y] * 1;
                    }
                    y++;
                }
                $('#totalPrice').html("<p>Sub Total: " + subTotal + "</p>")
                //subtract the new
                $('#finalpaypal').val(subTotal);
            });
            nextBoxId++;
            orderCap++;
            numOfBoxes++;
            $('#totalPrice').html("<p>Sub Total: " + subTotal + "</p>")
            halfPoundBoxes--;   
    }

您的代码仅在使用 alert() 时工作的原因是alert()操作为您的 jQuery AJAX 请求提供几秒钟的时间,以向 success() 回调函数返回值。

您应该将受标注函数影响的任何代码也移动到标注函数中,以便此代码以正确的顺序运行。


或者,您不能通过添加 async:false 来异步运行 AJAX 请求,但正如@Rocket所评论的那样,不建议这样做。

$.ajax({
  async: false,

您需要将代码放入函数中,并在 ajax 成功完成后运行它

...
$(function () {
  $.ajax({
    type: 'POST',
    url: 'phpscripts/api.php',      
    data: "",
    dataType: 'json',    
      success: function(rows)        
    {
    count = 0;
      for (var i in rows)
      {
        var row = rows[i];          
          product[count] = row[0];
          price[count] = row[1];
          size[count] = row[2];
          count++;
      }
      do_after_ajax();
    } 
  });
});
function do_after_ajax(){
        while (halfPoundBoxes > 0) {
        $("#boxes").append('<div id="b'+nextBoxId+'"></div>');
        $('#b'+nextBoxId).addClass('div-table-selection');
        ....
}

看起来您正在尝试对 ajax 返回的标记进行操作。该代码需要移动到 ajax 请求的成功回调中。警报调用使其正常工作的原因很简单,因为它会延迟其他所有内容足够长的时间以使页面完成加载。