2013-04-11 137 views
0

HTMLJavaScript的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。輸入年份& month後,我必須根據第1列的日期從第2列獲取信息,例如:「輸入年份:2002年,輸入月份:05 - 結果t必須是「中學」,因爲它在1999.09-2007.06之間。我看不出我的腳本有什麼問題,它總是給我提供虛假的信息。

回答

2

試試這個(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); 
     } 
    } 
} 
+0

非常感謝你,非常非常多的污穢物保!它完美的工作!:)))) – 2013-04-11 21:01:31