2017-03-13 1 views
1

나는 여러 개의 큰 테이블이있는 페이지에서 작업하고 있습니다. 내가 발견하고 테이블의 모든 셀이 스크립트 필터를 적용을 필터링하려면 여기JS로 여러 HTML 테이블 필터링

<script> 
function searchtable() { 
    var input, filter, table, tr, td, i; 
    input = document.getElementById("myInput"); 
    filter = input.value.toUpperCase(); 
    table = document.getElementById("myTable"); 
    tr = table.getElementsByTagName("tr"); 
    th = table.getElementsByTagName("th"); 

    for (i = 1; i < tr.length; i++) { 
    if (!tr[i].classList.contains('header')) { 
     td = tr[i].getElementsByTagName("td"), 
     match = false; 
     for (j = 0; j < td.length; j++) { 
     if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) { 
      match = true; 
      break; 
     } 
     } 
     if (!match) { 
     tr[i].style.display = "none"; 
     } else { 
     tr[i].style.display = ""; 
     } 
    } 
    } 
} 
</script> 

문제는 만 페이지의 첫 번째 테이블이 아닌 다른 사람의 코드가 작동. 모든 테이블마다 맞춤 스크립트를 반복하지 않는 편이 낫습니다. 스크립트를 개인화하여 여러 테이블에서 조회하는 방법에 대한 제안 사항이 있습니까?

편집 : 동일한 작업을 수행하는 다른 스크립트를 알고 있습니까?

+0

이 들어있는 <thead> 내부 <tr> 요소 atatched되어 있으리라 믿고있어. 당신이 만약 테이블에 객체 또는 배열 또는 그 안에 들어있는 데이터를 갖기 위해서는 배열 메소드를 사용하여 배열을 더 적합하게 만든 다음 테이블을 다시 렌더링하면됩니다.하지만 주제에 대해서는 모든 것을 매개 변수화 할 수 있으므로 함수는 'myInput' 및 'myTable'ids :'function searchTable (tableId) {}'다음에 각 테이블에 대해 올바른 ID가있는 이벤트 – Shilly

+0

@S hilly 배열 방법을 시도해 보겠습니다. 불행히도 나는 지금 그것을 할 수 없다. 나는 당신의 제안 (배열 방법의 사용과 ID의 사용)에 정말로 감사드립니다. 더 이상 제안이 있습니까? –

+0

자바 스크립트를 배우려고 하시거나 작업 코드가 필요합니까? 솔루션이 있지만 더 이상 코드를 인식하지 못합니다. – Shilly

답변

0

내가 변경 한 대부분의 지역을 설명하는 시도했습니다. 결국 코드 자체는 약간 더 짧지 만 조금 더 복잡합니다. 내가 올바르지 않은 가정을 한 경우 알려주십시오. (예를 들어, 우리가 모델을 발명 한 이유는,이 인 '헤더'클래스는 솔직히 <th> elements)

var searchTable = function searchTable(table, input) { 
 
    // Since we bound the input, we can use input.value to get the current words typed into the input. 
 
    var filter = input.value, 
 
     // A table has both a thead and a tbody. 
 
     // By only selecting the tr nodes from the body, we can remove the entire 'check if this is a header tr logic of `tr.classList.contains('header')` 
 
     // Keep in mind that querySelector returns a nodeList, so if we want to use array methods, we need to covnert it into a real array. 
 
     // The original code uses getElementsByTagName, which return a LIVE nodeList, watch out for this difference. 
 
     rows = Array.prototype.slice.call(table.querySelectorAll('tbody tr')); 
 
    rows.forEach(function(row) { 
 
     // Since we don't care in which cell the fitler is contained, we can just check the innerHTML of the entire row. 
 
     // This will only fail if the filter typed into the inputs is either 'tr' or 'td' 
 
     var hide = (row.innerHTML.indexOf(filter) === -1); 
 
     // The alternative is actually checking each cell, but this makes the script take longer: 
 
     // var hide = !Array.prototype.slice.call(row.querySelectorAll('td')).some(function(cell) { 
 
     //  return (cell.innerHTML.indexOf(filter) !== -1); 
 
     // }); 
 
     if (hide) row.classList.add('gone'); 
 
     else if (row.classList.contains('gone')) row.classList.remove('gone'); 
 
    }); 
 
    }, 
 
    // helper function that we can use to bind the searchTable function to any table and input we want 
 
    // We add an onchange event listener, passing it a bound version of searchTable. 
 
    bindSearch = function bindSearch(tableID, inputID) { 
 
    var input = document.querySelector(inputID), 
 
     table = document.querySelector(tableID); 
 
    if (table && input) input.addEventListener('change', searchTable.bind(null, table, input)); 
 
    else alert('Table or input does not exist.'); 
 
    }; 
 
// We can add as many individual inputs/tables as we want by just calling bindSearch with the right ids. 
 
bindSearch('#table1', '#input1'); 
 
bindSearch('#table2', '#input2');
.gone { 
 
    display: none; 
 
}
<input type="text" id="input1"> 
 
<table id="table1"> 
 
    <thead> 
 
    <tr> 
 
     <th>header 1</th> 
 
     <th>header 2</th> 
 
     <th>header 3</th> 
 
     <th>header 4</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td>Cell 1-1: foo</td> 
 
     <td>Cell 1-2: bar</td> 
 
     <td>Cell 1-3: baz</td> 
 
     <td>Cell 1-4: foo</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 2-1: apples</td> 
 
     <td>Cell 2-2: cherries</td> 
 
     <td>Cell 2-3: bananas</td> 
 
     <td>Cell 2-4: foo</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 3-1: cars</td> 
 
     <td>Cell 3-2: bar</td> 
 
     <td>Cell 3-3: planes</td> 
 
     <td>Cell 3-4: apples</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 4-1: baz</td> 
 
     <td>Cell 4-2: 2017</td> 
 
     <td>Cell 4-3: 2010</td> 
 
     <td>Cell 4-4: 2001</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 5-1: cars</td> 
 
     <td>Cell 5-2: 2017</td> 
 
     <td>Cell 5-3: foo</td> 
 
     <td>Cell 5-4: undefined</td> 
 
    </tr> 
 
    </tbody> 
 
</table> 
 
<br> 
 
<br> 
 
<input type="text" id="input2"> 
 
<table id="table2"> 
 
    <thead> 
 
    <tr> 
 
     <th>header 1</th> 
 
     <th>header 2</th> 
 
     <th>header 3</th> 
 
     <th>header 4</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td>Cell 1-1: foo</td> 
 
     <td>Cell 1-2: bar</td> 
 
     <td>Cell 1-3: baz</td> 
 
     <td>Cell 1-4: foo</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 2-1: apples</td> 
 
     <td>Cell 2-2: cherries</td> 
 
     <td>Cell 2-3: bananas</td> 
 
     <td>Cell 2-4: foo</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 3-1: cars</td> 
 
     <td>Cell 3-2: bar</td> 
 
     <td>Cell 3-3: planes</td> 
 
     <td>Cell 3-4: apples</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 4-1: baz</td> 
 
     <td>Cell 4-2: 2017</td> 
 
     <td>Cell 4-3: 2010</td> 
 
     <td>Cell 4-4: 2001</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Cell 5-1: cars</td> 
 
     <td>Cell 5-2: 2017</td> 
 
     <td>Cell 5-3: foo</td> 
 
     <td>Cell 5-4: undefined</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

+1

대단히 감사합니다 @ Shilly! 이제 커다란 변화가 될 것이라고 쓴 이유를 이해합니다.하지만 솔루션이 실제로 유용합니다! 스크립트를 사용 하겠지만 게시 된 코드가 작동하지 않는 이유를 찾으려고 노력할 것입니다. 다시 한 번 도움을 주신 모든 분들께 감사드립니다. –

+0

".toLowerCase()"를 "var filter = input.value"에 추가하면 대소 문자를 구분하지 않는 필터를 사용할 수 있습니다. –

+0

확실히. 그냥 원칙을 보여줍니다. 앱에 맞는 방식으로 필터 로직을 업데이트 할 수 있습니다. 또는 바인딩 매개 변수로 만들 수도 있으므로 다른 유형의 필터도 사용할 수 있습니다. :) 각 셀을 분명히 검사하는 코드는 주석에도 있습니다. – Shilly

0

HTML :

<table id="table2"> 
     <thead></thead> 
     <tbody> 
     <tr></tr> <tr></tr> 
     </tbody> 
    </table> 

JS는 :

var table1 = document.getElementById("table1"); 
    var table2 = document.getElementById("table2"); 

searchtable(table1); 
searchtable(table2); 

    function searchtable(table) { 
     var input, filter, table, tr, td, i; 
     input = document.getElementById("myInput"); 
     filter = input.value.toUpperCase(); 

     tr = table.getElementsByTagName("tr"); 
     th = table.getElementsByTagName("th"); 

     for (i = 1; i < tr.length; i++) { 
     if (!tr[i].classList.contains('header')) { 
      td = tr[i].getElementsByTagName("td"), 
      match = false; 
      for (j = 0; j < td.length; j++) { 
      if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) { 
       match = true; 
       break; 
      } 
      } 
      if (!match) { 
      tr[i].style.display = "none"; 
      } else { 
      tr[i].style.display = ""; 
      } 
     } 
     } 
    } 
+0

이것은 각 테이블을 동시에 필터링해야하는 경우가 아니라 각 테이블을 동시에 필터링해야하는 경우에만 작동합니다. 그러나 그렇습니다. 그것은 영업 이익에서 100 % 명확하지 않습니다. – Shilly

+0

테이블을 선택하고 해당 요소를 함수로 전달할 수 있습니다. –

+0

안녕하세요, 감사합니다. @BougarfaouiElhoucine, 직장에서 스크립트의 버전을 만들려고했지만 작동하지 않았습니다 ... 시도 했으므로 필터로 아무 것도하지 않았습니다 ... 모든 테이블에 ID를 추가했지만 작동하지 않았습니다 ... 여전히 도움을 주셔서 감사합니다! –