JavaScript的HTML表格解析(JavaScript HTML table parsing)

2019-10-18 00:22发布

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" />在那里我可以进入一年&month.After进入一年及一个月,我必须根据对例如第1列的日期从第二列获取信息:“输入年份:2002年,输入月:05 - 结果必然是“中学””,因为它1999.09-2007.06之间。 我看不出有什么不对我的脚本,它总是给我的虚假信息。

Answer 1:

尝试这种( 的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);
        }
    }
}


文章来源: JavaScript HTML table parsing