Javascript getElementById表现奇怪

use*_*202 4 javascript loops object plane

我正在使用for循环来循环一些具有起始值的元素(在平面上的座位).

这里是:
seatNum - 通过
startSeat 循环的座位数- 开始骑车的座位

我正在从"onsubmit"表单调用该函数.

问题出现在for循环中,当我尝试获取具有id命名约定"s1""s2""s3"等的元素时......"s45""s46"等...基于循环计数器添加到起始座位.计数从0(起始座位)到seatNum(多少个座位).

任何想法为什么id没有正确解决?所有其他工作正常,除了for循环中的最后一个.

是的我是编程的新手,所以我可能没有最佳实践,请在风格上宽容.

function check() {
    var startSeat;
    var fName = document.getElementById('fName').value
    var lName = document.getElementById('lName').value
    var address = document.getElementById('address').value
    var city = document.getElementById('city').value
    var state = document.getElementById('state').value
    var zip = document.getElementById('zip').value
    var phone = document.getElementById('phone').value
    var seatNum = document.getElementById('seatNumber').value
    var y=document.getElementById('seatList1').value;
    var z=document.getElementById('seatList2').value;

    if (z >= y) {
        startSeat = y;
    }
    else {
        startSeat = z;
    }

    if ( (fName == "") || (lName == "") || (address == "") || (phone == "") || (zip == "") || (state == "") || (city == "") ) {
        alert("You must fully complete the form");
        return false;
    }

    for (var i = 0; i < seatNum; i++) {
        if (document.getElementById("s"+(startSeat+i)).className=="taken"){
            alert("Selected seat(s) already booked.");
            return false;
        }
    else {
            continue;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

CMS*_*CMS 7

将您的yz变量转换为数字:

var y = +document.getElementById('seatList1').value;
var z = +document.getElementById('seatList2').value;

var startSeat = (z >= y) ? y : z; // or simply startSeat = Math.min(z,y);
Run Code Online (Sandbox Code Playgroud)

这将解决@Faruz指出的问题.


Far*_*ruz 5

我不确定,但也许startSeat + i汇总字符串而不是你想要的数学加法.尝试提醒屏幕:

alert(document.getElementById("s"+(startSeat+i))); 
Run Code Online (Sandbox Code Playgroud)

这是字段名称吗?