在jQuery中调用函数返回错误的结果

时间:2021-07-11 23:59:29

I have the following javascript code that runs fine if called outside the jQuery function on the bottom. I don't know what I am doing wrong.

如果在底部的jQuery函数之外调用,我有以下javascript代码运行正常。我不知道我做错了什么。

Bresenham Algorithm:

function bresenham(x0,y0,x1,y1){
    var bresenham = [];

    var x = 0;
    var dx = x1-x0;
    var dy = y1-y0;

    var D = 2 * dy - dx;
    bresenham.push(x0 + "," + y0);
    var y = y0;

    for (x = x0+1;x<=x1;x++){
        if (D>0){
            y = y+1;
            bresenham.push(x + "," + y);
            D = D + (2*dy - 2*dx);
        } else {
            bresenham.push(x + "," + y);
            D = D + (2*dy);
        }
    }
    return bresenham;
};

JQuery:

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = $('input[name=x0]').val();
        var y0 = $('input[name=y0]').val();
        var x1 = $('input[name=x1]').val();
        var y1 = $('input[name=y1]').val();

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});

If I input: x0 = 1, y = 0 and x1 = 15, y2 = 9

如果我输入:x0 = 1,y = 0且x1 = 15,y2 = 9

it outputs: ["1,0", "11,01", "12,01", "13,011", "14,0111", "15,0111"]

输出:[“1,0”,“11,01”,“12,01”,“13,011”,“14,0111”,“15,0111”]

1 个解决方案

#1


2  

I would change

我会改变

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = $('input[name=x0]').val();
        var y0 = $('input[name=y0]').val();
        var x1 = $('input[name=x1]').val();
        var y1 = $('input[name=y1]').val();

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});

to

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = parseInt($('input[name=x0]').val());
        var y0 = parseInt($('input[name=y0]').val());
        var x1 = parseInt($('input[name=x1]').val());
        var y1 = parseInt($('input[name=y1]').val());

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});

#1


2  

I would change

我会改变

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = $('input[name=x0]').val();
        var y0 = $('input[name=y0]').val();
        var x1 = $('input[name=x1]').val();
        var y1 = $('input[name=y1]').val();

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});

to

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = parseInt($('input[name=x0]').val());
        var y0 = parseInt($('input[name=y0]').val());
        var x1 = parseInt($('input[name=x1]').val());
        var y1 = parseInt($('input[name=y1]').val());

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});