简体   繁体   中英

error with javascript globals and jquery call back functions

i'm trying to make an array of value's to be checked to see if that value has been added before.

if it has show an alert. if it hasn't added it to the array and conduct a post ajax query to the server to retrieve a corresponding table row.

i'm mostly a novice when it comes to javascript and i'm finding it hard to debug because a fault in syntax breaks the entire script.

here is my code if someone see's an error could u tell me how to fix it.

also if you know a program to help with debugging java-script that would be really helpful.

I know that the jquery calls work fine because i added in the array check afterwards.

var selectedProductsArray = new array();
var selectedProductsCount = 0;

$(function() {
    $('.selectProductID').live('click', function(event) {

        var count = 0;
        var found = false;
        while(count < selectedProductsCount)
        {
            if(selectedProductsArray[count] == $(this).val())
            {
                found = true;
                break;
            }
            count++;
        }

        if(found)
        {
            alert("you can only add one line for each product.");
        }else{
            selectedProductsArray[selectedProductsCount] = $(this).val();
            selectedProductsCount++;
            $.post("order/getitem", "ProductID="+$(this).val(), function(data){
                $("#orderItems tbody").append(data);
                selectedProductsCount++;
            });
        }
        return false;
    });
});

Firstly, there is no "array" class so I'm surprised that you even getting passed that; you want:

var selectedProductsArray = new Array();

or

var selectedProductsArray = [ ];

Also, you don't need to keep computing $(this).val() over and over again, you should just say:

var count = 0;
var found = false;
var value = $(this).val();

above the while loop and reference value instead of $(this).val() in the rest. You're also incrementing selectedProductsCount twice when I think you only want to do it once, this will leave empty/null entries in your selectedProductsArray and that might confuse things later on.

I can't eye-ball any other glaring errors but that new array() one should be a show stopper. Hard to say without a fully functioning example.

Does order/getitem get called? Does it send anything back?

For debugging and trying things out:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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