2014-11-09 3 views
1

내 이전 질문과 관련이 있습니다.테이블의 선택된 행에서 최소 및 최대 수를 얻는 방법은 무엇입니까?

How to highlight/color multiple rows on selection?

<table id="toppings" border="1" cellpadding="2"> 
    <tr id="id1"> 
     <td>3</td> 
     <td>row12</td> 
     <td>row13</td> 
    </tr> 
    <tr id="id2"> 
     <td>12</td> 
     <td>row22</td> 
     <td>row23</td> 
    </tr> 
    <tr id="id3"> 
     <td>15</td> 
     <td>row32</td> 
     <td>row33</td> 
    </tr> 
    <tr id="id4"> 
     <td>22</td> 
     <td>row42</td> 
     <td>row43</td> 
</tr> 
<tr id="id5"> 
     <td>23</td> 
     <td>row52</td> 
     <td>row53</td> 
</tr> 
<tr id="id6"> 
    <td>55</td> 
    <td>row62</td> 
    <td>row63</td> 
</tr> 
</table> 

자바 스크립트 코드 :

//Get list of rows in the table 
var table = document.getElementById("toppings"); 
var rows = table.getElementsByTagName("tr"); 

var selectedRow; 

//Row callback; reset the previously selected row and select the new one 
function SelectRow(row) { 
    if (selectedRow !== undefined) { 
     selectedRow.style.background = "#d8da3d"; 
    } 
    selectedRow = row; 
    selectedRow.style.background = "white"; 
} 

//Attach this callback to all rows 
for (var i = 0; i < rows.length; i++) { 
    var idx = i; 
    rows[idx].addEventListener("click", function(){SelectRow(rows[idx])}); 
} 

하지만 행 선택을 위해 테이블에 이벤트를 추가하고 선택한 행에서 최소 및 최대 값 (첫 번째 열)을 얻으려고 노력했다이 시간 . 위의 표와 마찬가지로 중간 4 행을 선택하면 min = 12 및 max = 23을 가져야합니다. 어떻게 구현할 수 있습니까?

+1

이미 시도한 것을 추가 할 수 있습니까? –

답변

2

두 가지 기능을 사용할 수 있습니다. getMinValueExample()을 보여줍니다. 당신이 행을 선언 한 후이를 호출하는 경우

function getMinValueExample(rows){ 
var minValue = null; 
for (var i = 0; i < rows.length; i++){ 
    var firstTd = rows[i].getElementsByTagName('td')[0]; 
    var currentValue = parseInt(firstTd.innerHTML); 
    if(minValue == null || minValue > currentValue) 
     minValue = currentValue; 
} 
return minValue; 
} 

(일부 유형의 오류를 포함 할 수 있도록 테스트하지만 당신은 아이디어를 얻을해야되지 않음) 은 그래서 최소 값을 반환합니다. 그리고이 값을 호출하면 최대 값을 얻습니다.

function getMaxValueExample(rows){ 
var maxValue = null; 
for (var i = 0; i < rows.length; i++){ 
    var firstTd = rows[i].getElementsByTagName('td')[0]; 
    var currentValue = parseInt(firstTd.innerHTML); 
    if(maxValue == null || maxValue < currentValue) 
     maxValue = currentValue; 
} 
return maxValue; 
}