学生搜索项目jquery/javascript

Student search project jquery / javascript

本文关键字:javascript jquery 项目 搜索      更新时间:2023-09-26

我正在做一个项目,该项目要求我在一个包含学生姓名和电子邮件地址列表的页面上添加一个搜索栏,并且在提交表格后,只显示在搜索栏中键入了电子邮件地址或学生姓名字符的学生。

到目前为止,我已经附加了搜索栏,并启动了一个函数,该函数侦听按钮上的单击事件,并将输入中的值添加到变量中。

我想我可以做一个if语句,检查列表项是否包含我创建的输入变量,然后添加一个类,然后我可以稍后再做一个if语句,根据它包含的类来隐藏或显示。

$(document).ready(function() {
//set number of students to show on each page 
var inputValue;
var showStudents = 10;
//append search bar to the page
$(".page-header").append('<div class="student-search"><input placeholder="Search for students..."><button>Search</button></div>');
//add pagination to the page
$(".page").append('<div class="pagination"><ul></ul></div>');
//make page display 10 students at a time
//make search input only show students that contain that letter.
//use contains to add an ID?/class? to the student list item that matches the value in the input field.
//display the students that have said ID/class and hide the others. 
$("button").click(function() {
    //store the value of the input search into a variable
    inputValue = $("input").val();
    console.log(inputValue);
    //filter the list items by the input value and add CSS

        if ('.student-details h3:contains(inputValue)') {
        $('.student-details h3').addClass('showstudent')
    }
});

});

显然,我的问题是,一旦我写了这篇文章,它就会将类添加到所有项目中。student详细说明h3项目,而不仅仅是包含inputValue的项目,我不能使用"this",因为它只是将类添加在按钮中。这是最好的编码方式吗?我是否应该将我的学生列表转换为一个数组,并让输入值搜索该数组,然后将结果返回到一个新数组中?我有点迷路了!谢谢你的帮助。

您可以尝试这种方法:

$('.student-details h3').each(function() {
    if ($(this).text() == inputValue) {
        $(this).addClass('showstudent');
    }
}