Um exemplo a seguir de um objeto para que os usuários pesquisem nela usando palavras / frases, retornando os objetos:
var items = []; var obj = { index: 1, content: "This is a sample text to search." }; items.push(obj); obj = { index: 2, content: "Here's another sample text to search." }; items.push(obj);
Fica assim
<script> var items = []; var obj = { index: 1, content: "This is a sample text to search." }; items.push(obj); obj = { index: 2, content: "Here's another sample text to search." }; items.push(obj); function find(items, text) { text = text.split(' '); return items.filter(function(item) { return text.every(function(el) { return item.content.indexOf(el) > -1; }); }); } console.log(find(items, 'text')) // both objects console.log(find(items, 'another')) // object 2 console.log(find(items, 'another text')) // object 2 console.log(find(items, 'is text')) // object 1 </script>
*veja no console F12 ou Fn+F12
Veja outro exemplo
<div id="result"></div> <script> var items = []; var obj = { index: 1, content: "aqui tem master e joel" }; items.push(obj); obj = { index: 2, content: "aqui tem joel e tem master" }; items.push(obj); obj = { index: 3, content: "aqui tem joe e mast" }; items.push(obj); function find(items, text) { text = text.split(' '); return items.filter(function(item) { return text.every(function(el) { return item.content.indexOf(el) > -1; }); }); } //como usar var x = (find(items, 'master joel')); document.getElementById('result').innerHTML = x.length +' resultados<br>'; ii = 0; while(ii < x.length){ document.getElementById('result').innerHTML+= x[ii].content+"<hr>"; ii++;} // document.getElementById('result').innerHTML+= x[0].content; // para pegar só o primeiro resultado apague em cima e habilite essa </script>
Outro exemplo, que mostra somente 1.
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <input type="text" id="text" onKeyUp="myFunction()"> <div id="result"></div> <script> function myFunction() { var plv = document.getElementById('text').value.split(' '); var whiteList = plv; //var whiteList = ['css', 'js']; var events = [{ file: 'css/style.css', type: 'js' }, { file: 'js/app.js', type: 'js' }, { file: 'index/html.html', type: 'html' }]; var fileList = events.filter(function(event) { return whiteList.indexOf(event.type) > -1 }) document.getElementById('result').innerHTML= fileList[0].file; } </script>
<< Anterior exemplo simples de contar elementos filho em div usando jquery
Deixe um comentário