2

HTML

<table id="table">
<tr>
<td>1999.09-2007.06</td>
<td> Secondary School </td>
</tr>
<tr>
<td>2007.09-2011.06</td>
<td> College </td>
</tr>
<tr>
<td>2011.09-2015.06</td>
<td> University</td>
</tr>
</table>


<form autocomplete="on">
<p/>
<label>Year</label>
<input type="text" id="year" name="year" autofocus/>
<p/>
<label>Month</label>
<input type="text" name="month" id="month" />
<p/>
</form>
<input type="button" onClick="method()" />

JavaScript

function method(){
var year = document.getElementById("year").value;
var month = document.getElementById("month").value;
var data = new Date(year,month-1,1);
var dataTable = document.getElementById("table");
var cells = dataTable.querySelectorAll("td");
var cells2 = dataTable.querySelectorAll("td+td");

for (var i = 0; i < cells.length; i++){
    var mikro = cells[i].firstChild.data.split("-");
    var place = cells2[i].firstChild.data;
    var firstData = mikro[0].split(".");
    var secondData = mikro[1].split(".");
    var data1 = new Date(firstData[0],firstData[1]-1,1);
    var data2 = new Date(secondData[0],secondData[1]-1,1);
    if(data1<=data && data2>=data){     
        alert(place);
        }
    }
}

在这里,我在表格中有 2 列,我想创建脚本来帮助我从中查找信息:我有<input type="text" id="year" name="year" autofocus/><input type="text" name="month" id="month" />我可以在哪里输入年和月。输入年和月后,我必须根据第 2 列获取信息第一列的日期例如:“输入年份:2002,输入月份:05 - 结果必须是'中学'”,因为它介于 1999.09-2007.06 之间。我看不出我的脚本有什么问题,它总是给我错误的信息。

4

1 回答 1

4

试试这个(jsfiddle),每次将单元格索引增加 2,并使用更简单的td选择器:

function method () {
    var year = document.getElementById("year").value;
    var month = document.getElementById("month").value;
    var data = new Date(year, month - 1, 1);
    var dataTable = document.getElementById("table");
    var cells = dataTable.querySelectorAll("td");

    for (var i = 0; i < cells.length; i+=2) {
        var mikro = cells[i].firstChild.data.split("-");
        var place = cells[i+1].firstChild.data;
        console.log(mikro, place);
        var yearMonth1 = mikro[0].split(".");
        var yearMonth2 = mikro[1].split(".");
        var data1 = new Date(yearMonth1[0], yearMonth1[1] - 1, 1);
        var data2 = new Date(yearMonth2[0], yearMonth2[1] - 1, 1);
        if (data1 <= data && data2 >= data) {
            alert(place);
        }
    }
}
于 2013-04-11T20:30:57.047 回答