jQuery搜索功能

时间:2017-09-06 23:26:25

标签: javascript jquery

您好我正在构建一个在jQuery中有页面导航和搜索栏的项目。

我无法使我的搜索功能正常工作,并且我不确定ID元素或每个功能是否存在问题。我收到了("抱歉,找不到学生!")的消息,表示任何匹配或不匹配的内容。所以我认为if语句在搜索功能中寻找匹配可能会有问题 - 但不确定。

我正在向我的html动态添加搜索框,如下所示:

function appendSearchBox(){
    var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
    $(".students").after(search);

    // Add click event handler
    $("button").click(function() {
        searchList();
    });

}

这是我的html对于学生列表的样子:

  <div class="page">
      <div class="page-header cf">
        <h2 class="students">Students</h2>

      </div>
      <ul class="student-list">
        <li class="student-item cf">
            <div class="student-details">
                <img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
                <h3>iboya vat</h3>
                <span class="email">iboya.vat@example.com</span>
            </div>
            <div class="joined-details">
                   <span class="date">Joined 07/15/15</span>
           </div>
        </li>
</ul>

然后这是实际的搜索功能:

var listStudents = $(".student-list li");
var numStudents = listStudents.length;

function searchList() {
    var matched = [];
    // Obtain the value of the search input
    input = $("#search").val()
    // remove the previous page link section
    $('.pagination').hide();
    // Loop over the student list, and for each student…
    listStudents.each(function(){
        // ...obtain the student’s name…
        var name = $(this).find("h3").val();
        // ...and the student’s email…
        var email = $(this).find(".email").val();
        // ...if the search value is found inside either email or name…
        if (name.includes(input) || email.includes(input))  {
             // ...add this student to list of “matched” student
             matched.push($(this).parent());
             }
     });
     // If there’s no “matched” students…
     if (matched.length === 0){
         // ...display a “no student’s found” message
            var message = ("Sorry, no student's found!");
            $(".student-list").hide();
            $(".student-list").after(message);

     if (matched.length > 10) {
        // ...call appendPageLinks with the matched students
        appendPageLinks(matched);
        }
        // Call showPage to show first ten students of matched list
        showPage(1, matched);
     }


}

添加实际显示学生并添加导航的功能

function showPage(pageNum, listStudents) {
    // first hide all students on the page
    pageNum = parseInt(pageNum);
    listStudents.hide();
    // Then loop through all students in our student list argument
    listStudents.each(function(index){
    // if student should be on this page number
        if ((index >= ((pageNum*10)-9)) &&  (index <= (pageNum*10))) {
        // show the student
            $(this).show();
            }
    });

 }

function getNumPages(numStudents){
    numPages = Math.ceil(numStudents/10);
    return numPages;
    }


function appendPageLinks(numStudents) {
    // determine how many pages for this student list
    pages  = getNumPages(numStudents);
    // create a page link section
    var nav = "<div class='pagination'><ul>"
    for (i=1; i<pages+1; i+=1){
        nav += ("<li>" + "<a href='#' id=" + i + ">" + i + "</a>" + "</li>");
    };
    nav += ("</ul></div>");
    $(".student-list").after(nav);

    // define what happens when you click a link
    var active = $('.pagination a').click(function(){
        // Use the showPage function to display the page for the link clicked
        var id = $(this).attr('id');
        showPage(id,listStudents);
        // mark that link as “active”
        active.removeClass('active');
        $(this).addClass("active");
        });
}

这是我如何调用函数:

appendSearchBox();
showPage(1, listStudents);
appendPageLinks(numStudents);

更新 - 我已经更改了代码以删除val并放入以获取文本。

不确定是什么问题,但如果我有正确的匹配就会出现 - 它正在运行(因为分页消失)但学生不会在页面上进行更改。如果没有匹配,那么我收到错误消息,但错误控制台正在说

Uncaught TypeError: listStudents.hide is not a function
    at showPage (main.js:8)

我不确定这是否与我如何通过匹配的&#39;列出?

2 个答案:

答案 0 :(得分:0)

h3span代码没有任何价值,但是文字内容,请替换:

    var name = $(this).find("h3").val();
    // ...and the student’s email…
    var email = $(this).find(".email").val();

使用:

    var name = $(this).find("h3").text();
    // ...and the student’s email…
    var email = $(this).find(".email").text();

答案 1 :(得分:0)

您正在使用val()方法读取h3和span(电子邮件)的内部文本。它应该是text()。此外,每当您找不到学生时,您都会在学生列表后面添加消息。您可以使用一个span代码并根据搜索结果隐藏/显示。

&#13;
&#13;
function appendSearchBox() {
	var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
	$(".students").after(search);

	// Add click event handler
	$("button").click(function () {
		searchList();
	});
}

$(document).ready(function () {
	appendSearchBox();
});

function searchList() {
	var listStudents = $(".student-list li");
	var numStudents = listStudents.length;
	$(".student-list").show();
	$("#message").hide();

	var matched = [];
	// Obtain the value of the search input
	input = $("#search").val()
	// remove the previous page link section
	$('.pagination').hide();

	// Loop over the student list, and for each student…
	listStudents.each(function () {
		// ...obtain the student’s name…
		var name = $(this).find("h3").text();
		// ...and the student’s email…
		var email = $(this).find(".email").text();
		// ...if the search value is found inside either email or name…
		if (name.includes(input) || email.includes(input)) {
			// ...add this student to list of “matched” student
			matched.push($(this).parent());
		}
	});
	// If there’s no “matched” students…
	if (matched.length === 0) {
		// ...display a “no student’s found” message
		var message = ("Sorry, no student's found!");
		$(".student-list").hide();
		$("#message").show();

		if (matched.length > 10) {
			// ...call appendPageLinks with the matched students
			appendPageLinks(matched);
		}
		// Call showPage to show first ten students of matched list
		showPage(1, matched);
	}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="page">
	<div class="page-header cf">
		<h2 class="students">Students</h2>
	</div>

	<ul class="student-list">
		<li class="student-item cf">
			<div class="student-details">
				<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
				<h3>iboya vat</h3>
				<span class="email">iboya.vat@example.com</span>
			</div>
			<div class="joined-details">
				<span class="date">Joined 07/15/15</span>
			</div>
		</li>
	</ul>

	<span id="message" style="display:none;"><br/>Sorry, no student's found!</span>
</div>
&#13;
&#13;
&#13;