티스토리 뷰
몇 가지 문제가있었습니다.
stringValue.onkeyup
-stringValue는 값입니다. 당신은 그것을 onkeyup 할 수 없습니다.var eachStudent = document.querySelector(".student-item");
student-item
클래스 와 함께 가장 먼저 가져옵니다 .querySelectorAll
jquery의 $ ( '. find-item') 을 사용 하거나 사용해야합니다.if (name.toUpperCase().indexOf(filter) == 0)
indexOf는 필터가 이름의 시작 부분에 있으면 0을 반환합니다. 인덱스 0에서 발견되면 0이 일치합니다. -1에 대해 확인해야합니다. 이는 전혀 발견되지 않았 음을 의미합니다.
그렇지 않으면 어느 정도 효과가 있었고 잘했습니다.
또한 더 빨리 고칠 수 있도록 Jquery를 추가했습니다. 순수 자바 스크립트 사용을 고집한다면 편집 할 수있을 것입니다.
여기에서 확인하세요 : http://codepen.io/anon/pen/WGrrXW?editors=1010 . 결과 코드는 다음과 같습니다.
var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");
//Recreate Search Element in Js
var searchBar = function createBar(searchString) {
var studentSearch = document.createElement("div");
var input = document.createElement("input");
var searchButton = document.createElement("button");
input.type = "text";
var txtNode = document.createTextNode("Search");
if (typeof txtNode == "object") {
searchButton.appendChild(txtNode);
}
studentSearch.setAttribute("class", "student-search");
input.setAttribute("id", "inputSearch");
//append these elements to the page
studentSearch.appendChild(input);
studentSearch.appendChild(searchButton);
input.placeholder = "Type name here..";
return studentSearch;
}
var searchFunction = function searchFeature(searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
inputString.onkeyup = function() {
//toUpperCase to make it case insensitive
var filter = $(this).val().toUpperCase()
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = $(eachStudent[i]).find('h3').text()
console.log(name, filter, name.toUpperCase().indexOf(filter))
//display all the results where indexOf() does not return -1
if (name.toUpperCase().indexOf(filter) != -1)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}
}
function addElements() {
console.log('Add search bar, trying to anyway...')
pageHeader.appendChild(searchBar());
// page.appendChild(paginationFilter());
onLoad();
}
window.onload = addElements;
window.onLoad = searchFunction;
출처
https://stackoverflow.com/questions/39917192