如何使用香草JavaScript实现搜索功能? [英] How to implement search feature using vanilla javascript?

查看:81
本文介绍了如何使用香草JavaScript实现搜索功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了联系人列表应用程序,显示联系人详细信息。我想实现基于名称的搜索功能。现在,当我输入某人的名字时,它应该动态地更改联系人列表。



index.html:



  var array = []; function Person(fullName,number,group){this.fullName = fullName; this.number = number; this.group = group; array.push(this);} Person.prototype.getFullName = function(){return this.fullName +''+ this.number +''+ this.group;} var p1 = new Person(Jonathan Buell,5804337551,家族); var p2 = new Person(Patrick Daniel,8186934432,work); console.log(array); / * function save(){localStorage.setItem(array,JSON.stringify(array) );} function submitToDb(){var person = new Person(nameInput.value,numberInput.value,groupInput.value); (); var refresh();} var storedArray = JSON.parse(localStorage.getItem(array)); function loadLocalStorage(){for(var i in storedArray){array [i] = storedArray [i] } // refresh(); } loadLocalStorage(); * / function showContacts(){for(var i in array){var id = i; contactlist.innerHTML + =`< ul> < DIV> < p>名称:`+ array [i] .fullName +`< / p> < p>编号:`+ array [i] .number +`< / p> < p>群组:`+ array [i] .group +`< / p> < button type =buttonclass =btn btn-warningonclick =editContact(`+ id +`)>编辑< / button> < button type =buttonclass =btn btn-danger>删除< / button> < / DIV> `}} showContacts(); function addNew(){document.getElementById(search)。style.display ='none'; document.getElementById(contactlist)。style.display ='none'; document.getElementById(editcontact)。style.display ='none'; document.getElementById(addnewcontact)。style.display =''; document.getElementById(addnewcontact)。innerHTML =`< form> < div class =form-group> < label for =inputName>名称< / label> < input type =textclass =form-controlid =inputNamearia-describedby =namehelpplaceholder =Enter Name> < / DIV> < div class =form-group> < label for =inputNumber> Number< / label> < input type =textclass =form-controlid =inputNumberaria-describedby =numberhelpplaceholder =Enter Number> < / DIV> < div class =form-group> < label for =inputGroup> Group< / label> < input type =textclass =form-controlid =inputGrouparia-describedby =grouphelpplaceholder =Enter Group> < / DIV> < button type =submitclass =btn btn-primaryonclick =submittoDB()>提交< / button> < /形式> `;} function editContact(id){document.getElementById(search)。style.display ='none'; document.getElementById(contactlist)。style.display ='none'; document.getElementById(editcontact)。style.display =''; document.getElementById(editcontact)。innerHTML =`< form> < div class =form-group> < label for =InputName2>名称< / label> < input type =textclass =form-controlid =inputName2aria-describedby =namehelpvalue =`+ array [id] .fullName +`> < / DIV> < div class =form-group> < label for =InputNumber2> Number< / label> < input type =textclass =form-controlid =inputNumber2value =`+ array [id] .number +`> < / DIV> < div class =form-group> < label for =InputGroup2> Group< / label> < input type =textclass =form-controlid =inputGroup2value =`+ array [id] .group +`> < / DIV> < button type =submitclass =btn btn-primaryonclick =saveMe(`+ id +`)>提交< / button> < /形式> `;} / * function saveMe(id){array [id] .fullName = document.getElementById(nameInput2).value; array [id] .number = document.getElementById(numberInput2)。value; array [id] .group = document.getElementById(groupInput2)。value;} * / function deleteMe(id){array.splice(id,1); // refresh(); // save();}  

.header {display: flex;}。header> div {float:left;}。header .title {padding-left:400px;}。header .dropdown {padding-top:20px; padding-left:20px;}。header .button {padding-left:500px; padding-top:5px;}。glyphicon-plus-sign {font-size:50px;}#search form .input-group {padding-left:30px; padding-right:30px; padding-bottom:10px;}。input-group {padding-top:20px;}。form-group {padding-left:30px; padding-right:30px;} form .btn-primary {margin-left:30px;}

 <!DOCTYPE html>< html>< head> < title>联系人列表应用< / title> < meta charset =utf-8> < meta name =viewportcontent =width = device-width,initial-scale = 1> < link rel =stylesheethref =https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css> < script src =https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js>< / script> < script src =https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js>< / script> < link rel =stylesheettype =text / csshref =index.css> < script type =text / javascriptsrc =app.js>< / script>< / head>< body> < div class =header> < div id =dropdown> < div class =dropdown> < button class =btn btn-primary dropdown-toggletype =buttondata-toggle =dropdown>按组排序< span class =caret>< / span>< / button> ; < ul class =dropdown-menu> < li>< a href =#>全部< / a>< / li> < li>< a href =#>工作< / a>< / li> < li>< a href =#>家族< / a>< / li> < / UL> < / DIV> < / DIV> < div class =title> < h2>所有联系人< / h2> < / DIV> < div class =buttonid =addButton> < p为H. < a href =#> < span class =glyphicon glyphicon-plus-signonclick =addNew()>< / span> < / A> < / p为H. < / DIV> < / DIV> < div id =search> <形式> < div class =input-group> < input type =textclass =form-controlplaceholder =Search> < div class =input-group-btn> < button class =btn btn-defaulttype =submit> < i class =glyphicon glyphicon-search>< / i> < /按钮> < / DIV> < / DIV> < /形式> < / DIV> < div id =contactlist> < / DIV> < div id =addnewcontact> < / DIV> < div id =editcontact> < / DIV> < / body>< / html>  

使用 id =contactlist,id =editcontactid =addnewcontact动态填充3个div标记 $ b

应用现场演示:

解决方案

你的代码片段中的许多不相关的代码。但是,通常, Array.filter 是你的朋友:

 常量联系人= [
{全名:'Jonathan Buell',编号:5804337551, :'family'},
{fullName:'Joey无论',编号:5454355351,组:'family'},
{全名:'Patrick Daniel',编号:8186934432,组:'work' }
];

contacts.filter(contact => contact.fullName.startsWith('Jo'));
/ *
结果:
[
{全名:'Jonathan Buell',编号:5804337551,组:'family'},
{fullName:'Joey whatever ',number:5454355351,group:'family'}
]
* /

...但是 startsWith 区分大小写,它会返回一个空数组''''。



一个解决方案是使用正则表达式代替:

  contacts.filter(contact => contact.fullName.match(/ ^ jo /一世)); 
contacts.filter(contact => contact.fullName.match(/ ^ Jo / i));

/ *
'i'标志使匹配不区分大小写。
在这两种情况下,结果与上面相同。
* /

您可以轻松创建过滤功能:

  const filterContacts =(startLetters,contacts)=> 
contacts.filter(contact =>
contact.fullName.match(new RegExp(`^ $ {startLetters}`,'i'))
);

...并像这样使用它:

  filterContacts('jo',contacts); 
$ b / *
结果:
[
{全名:'Jonathan Buell',号码:5804337551,group:'family'},
{fullName :'Joey无论',号码:5454355351,group:'family'}
]
* /

filterContacts('pat',contacts);
$ b $ * / $
结果:
[
{全名:'Patrick Daniel',编号:8186934432,小组:'工作'}
]
* /

...当然会将它绑定到搜索输入变更:

  searchInput.addEventListener('input',function(event){
const startLetters = event.target.value;
const filteredContacts = filterContacts(startLetters,contacts);
// ...并在模板中显示filteredContacts
});

工作片段(需要支持ES2015的现代浏览器):

< li> $ {contact.fullName},$ {contact.number}< / li> ');});});

< input />< ul>< / ul>

小额奖金:如果你想搜索任何地方,不只是从一开始(所以 会匹配'帕特里克达 ni el')) ,只需从正则表达式中删除 ^


I have made a contact list app which shows the contact details. I want to implement search feature based on name. Now when I type in someone's name it should dynamically change the contact list.

index.html :

var array = [];
function Person(fullName, number, group) {
        this.fullName = fullName;  
        this.number = number;
        this.group =  group;
        array.push(this);
}

Person.prototype.getFullName = function() {
    return this.fullName+' '+this.number+' '+this.group;
}

var p1 = new Person("Jonathan Buell",5804337551,"family");
var p2 = new Person("Patrick Daniel",8186934432,"work");

console.log(array);

/*
function save() {
    localStorage.setItem("array", JSON.stringify(array));
}


function submitToDb() {
    var person = new Person(nameInput.value, numberInput.value, groupInput.value);
   // refresh();
} 

var storedArray = JSON.parse(localStorage.getItem("array"));
function loadLocalStorage() {
    for(var i in storedArray){
        array[i] = storedArray[i]; 
    }
   // refresh(); 
}
loadLocalStorage();
*/

function showContacts() {
    for(var i in array){
        var id = i;
        contactlist.innerHTML +=
        `
        <ul>
        <div>
        <p>Name: `+ array[i].fullName +`</p>
        <p>Number: `+ array[i].number +`</p>
        <p>Group: `+ array[i].group +`</p>
        <button type="button" class="btn btn-warning" onclick="editContact(`+ id +`)">Edit</button>
        <button type="button" class="btn btn-danger">Delete</button>
        </div>
        `
    }
}

showContacts();

function addNew() {
	document.getElementById("search").style.display = 'none';
	document.getElementById("contactlist").style.display = 'none';
	document.getElementById("editcontact").style.display = 'none';
	document.getElementById("addnewcontact").style.display = '';
	document.getElementById("addnewcontact").innerHTML = 
	`
	<form>
      <div class="form-group">
        <label for="inputName">Name</label>
        <input type="text" class="form-control" id="inputName" aria-describedby="namehelp" placeholder="Enter Name">
      </div>
       <div class="form-group">
        <label for="inputNumber">Number</label>
        <input type="text" class="form-control" id="inputNumber" aria-describedby="numberhelp" placeholder="Enter Number">
      </div>
      <div class="form-group">
        <label for="inputGroup">Group</label>
        <input type="text" class="form-control" id="inputGroup" aria-describedby="grouphelp" placeholder="Enter Group">
      </div>
      <button type="submit" class="btn btn-primary" onclick="submittoDB()">Submit</button>
    </form>
	`;
}


function editContact(id) {
    document.getElementById("search").style.display = 'none';
    document.getElementById("contactlist").style.display = 'none';
    document.getElementById("editcontact").style.display = '';
    document.getElementById("editcontact").innerHTML = 
        `
        <form>
          <div class="form-group">
            <label for="InputName2">Name</label>
            <input type="text" class="form-control" id="inputName2" aria-describedby="namehelp" value="`+array[id].fullName+`" >
          </div>
          <div class="form-group">
            <label for="InputNumber2">Number</label>
            <input type="text" class="form-control" id="inputNumber2" value="`+array[id].number+`">
          </div>
          <div class="form-group">
            <label for="InputGroup2">Group</label>
            <input type="text" class="form-control" id="inputGroup2" value="`+array[id].group+`">
          </div>
          <button type="submit" class="btn btn-primary" onclick="saveMe(`+id+`)">Submit</button>
        </form>
        `;
}

/*
function saveMe(id) {
    array[id].fullName = document.getElementById("nameInput2").value;
    array[id].number = document.getElementById("numberInput2").value;
    array[id].group = document.getElementById("groupInput2").value;
}
*/

function deleteMe(id) {
    array.splice(id, 1);
   // refresh();
   // save();
}

.header{
	display:flex;
}

.header>div{
	float: left;
}

.header .title{
	padding-left: 400px;
}

.header .dropdown{
	padding-top: 20px;
	padding-left: 20px;
}

.header .button{
	padding-left: 500px;
	padding-top: 5px;
}

.glyphicon-plus-sign{
	font-size: 50px;
}

#search form .input-group{
	padding-left: 30px;
	padding-right: 30px;
	padding-bottom: 10px;
}

.input-group{
	padding-top: 20px;
}

.form-group{
	padding-left: 30px;
	padding-right: 30px;
}

form .btn-primary{
	margin-left: 30px;
}

<!DOCTYPE html>
<html>
<head>
  <title>Contact List App</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script type="text/javascript" src="app.js"></script>
</head>
<body>

  <div class="header">
    
	    <div id="dropdown">
	       <div class="dropdown">
	          <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sort by Group
	          <span class="caret"></span></button>
	          <ul class="dropdown-menu">
	            <li><a href="#">All</a></li>
	            <li><a href="#">Work</a></li>
	            <li><a href="#">Family</a></li>
	          </ul>
	        </div> 
	    </div>

	    <div class="title">
	      <h2>All Contacts</h2>
	    </div>

	    <div class="button" id="addButton">
	      <p>
	        <a href="#">
	          <span class="glyphicon glyphicon-plus-sign" onclick="addNew()"></span>
	        </a>
	      </p>
	    </div>
    
  </div>

  <div id="search">
     <form>
      <div class="input-group">
        <input type="text" class="form-control" placeholder="Search">
        <div class="input-group-btn">
          <button class="btn btn-default" type="submit">
            <i class="glyphicon glyphicon-search"></i>
          </button>
        </div>
      </div>
    </form> 
  </div>


  <div id="contactlist" >
        
  </div>


  <div id="addnewcontact">
  
    
  </div>


  <div id="editcontact">
    
  </div>


  
</body>
</html>

Currently I am dynamically populating 3 div tag with id="contactlist" , id="editcontact" id="addnewcontact"

App live demo : https://jsfiddle.net/ap8xvoo7/

screenshot of app:

解决方案

Lot of irrelevant code in your snippets. But, generally, Array.filter is your friend:

const contacts = [
  { fullName: 'Jonathan Buell', number: 5804337551, group: 'family' },
  { fullName: 'Joey Whatever', number: 5454355351, group: 'family' },
  { fullName: 'Patrick Daniel', number: 8186934432, group: 'work' }
];

contacts.filter(contact => contact.fullName.startsWith('Jo'));
/*
Result:
  [
    { fullName: 'Jonathan Buell', number: 5804337551, group: 'family' },
    { fullName: 'Joey Whatever', number: 5454355351, group: 'family' }
  ]
*/

…but startsWith is case-sensitive, it would return an empty array for lowercase 'jo'.

One solution is to use regex instead:

contacts.filter(contact => contact.fullName.match(/^jo/i));
contacts.filter(contact => contact.fullName.match(/^Jo/i));

/*
The 'i' flag makes matching case-insensitive.
Result is the same as above in both cases. 
*/

You can create a filtering function easily:

const filterContacts = (startLetters, contacts) =>
  contacts.filter(contact =>
    contact.fullName.match(new RegExp(`^${startLetters}`, 'i'))
  );

…and use it like this:

filterContacts('jo', contacts);

/*
Result:
  [
    { fullName: 'Jonathan Buell', number: 5804337551, group: 'family' },
    { fullName: 'Joey Whatever', number: 5454355351, group: 'family' }
  ]
*/

filterContacts('pat', contacts);

/*
Result:
  [
     { fullName: 'Patrick Daniel', number: 8186934432, group: 'work' }
  ]
*/

…and of course bind it to search input change:

searchInput.addEventListener('input', function(event) {
    const startLetters = event.target.value;
    const filteredContacts = filterContacts(startLetters, contacts);
    // …and display filteredContacts in your template
});

Working snippet (requires a modern browser with ES2015 support):

document.addEventListener('DOMContentLoaded', function() {
  const contacts = [
    { fullName: 'Jonathan Buell', number: 5804337551, group: 'family' },
    { fullName: 'Joey Whatever', number: 5454355351, group: 'family' },
    { fullName: 'Patrick Daniel', number: 8186934432, group: 'work' }
  ];

  const filterContacts = (startLetters, contacts) =>
    contacts.filter(contact =>
      contact.fullName.match(new RegExp(`^${startLetters}`, 'i'))
    );

  // populate the list with all contacts after the page is loaded:
  const contactList = document.querySelector('ul');
  contactList.innerHTML = contacts
    .map(contact => `<li>${contact.fullName}, ${contact.number}</li>`)
    .join('');
    
  // filter contacts when user types something into input, and replace the list contents with filtered contacts:  
  document.querySelector('input').addEventListener('input', function(event) {
    const startLetters = event.target.value;
    const filteredContacts = filterContacts(startLetters, contacts);
    contactList.innerHTML = filteredContacts
      .map(contact => `<li>${contact.fullName}, ${contact.number}</li>`)
      .join('');
  });
});

<input />
<ul></ul>

A small bonus: if you want to search anywhere, not just from the start (so 'ni' would match 'Patrick Daniel'), just remove ^ from the regex.

这篇关于如何使用香草JavaScript实现搜索功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆