【问题标题】:Javascript search and display divs with matching keywordsJavascript 搜索并显示具有匹配关键字的 div
【发布时间】:2014-12-17 02:08:19
【问题描述】:

我在寻找什么:

我正在努力为用户创建一种简单的方法来搜索人员列表,并让结果立即显示在搜索字段下方。结果必须显示“接近”的结果,而不是精确的。例如:用户搜索“Mr. Smith”,显示如下现有结果:“John Smith”(由于没有“Mr. Smith”条目,所以显示了一个带有关键字“smith”的条目)

我有什么:

我有一个工作代码,允许用户输入一些字符,并显示包含与输入匹配的字符串的所有 div(参见 jsfiddle:http://jsfiddle.net/891nvajb/5/ 代码也在下面) 不幸的是,这只会显示完全匹配的结果。

<body>
	<input type="text" id="edit_search" onkeyup="javascript: find_my_div();">
	<input type="button" onClick="javascript: find_my_div();" value="Find">
        
<script>

function gid(a_id) {
	return document.getElementById (a_id)	;
}

  function close_all(){
  
  	for (i=0;i<999; i++) {
  		var o = gid("user_"+i);
  		if (o) {
  			o.style.display = "none";
  		}
  	}
  
  }


  function find_my_div(){ 
  	close_all(); 
  	
	var o_edit = gid("edit_search");
	var str_needle = edit_search.value;
	str_needle = str_needle.toUpperCase();
  
	if (str_needle != "") {
		for (i=0;i<999; i++) {
	  	var o = gid("user_"+i);
	  	if (o) { 
	  		
	  		var str_haystack = o.innerHTML.toUpperCase();
	  		if (str_haystack.indexOf(str_needle) ==-1) {
	  			// not found, do nothing
	  		}
	  		else{
	  			o.style.display = "block";
		  		}	
  			}
  		}
  	}
  
  }
</script>
    
<div id="user_0" style="display:none">Andy Daulton<br/>Owner Nissan<br/><br/></div>
<div id="user_1" style="display:none">Doug Guy<br/>Bug Collector<br/><br/></div>
<div id="user_2" style="display:none">Sam Hilton<br/>Famous Celebrity in Hollywood<br/><br/></div>
<div id="user_3" style="display:none">Don Grey<br/>Old man<br/><br/></div>
<div id="user_4" style="display:none">Amy Hinterly<br/>Cook<br/><br/></div>
<div id="user_5" style="display:none">Gary Doll<br/>Racecar Driver<br/><br/></div>
<div id="user_6" style="display:none">Tod Akers<br/>Football Player<br/><br/></div>
<div id="user_7" style="display:none">Greg Barkley<br/>Interior designer<br/><br/></div>
<div id="user_8" style="display:none">Alen Simmons<br/>8th place winner<br/><br/></div>

【问题讨论】:

  • 我无法在您声称有效的 JSFIDDLE 中重现“完全匹配”行为......您能否举例说明您在搜索时搜索的内容... ..
  • 嵌入代码似乎可以工作; "ton" 返回 Daulton 和 Hilton...?
  • 您只想优先考虑几个匹配的单词而不是更少?或者,Smoth 先生也应该归还 John Smith?
  • @Phani 示例:“dy da”将显示“Andy Daulton”,因为该字符串包含在该结果中。然而,如果您输入“andy smith”,则不会出现任何内容,即使结果中有“andy”。所以它不是单独查看关键字(这就是我想要的),而只是输入的确切字符串。
  • @juvian 如果“smooth”是 John Smith 结果中的关键字,那么他会出现,否则不会出现。

标签: javascript html search user-input displayobject


【解决方案1】:

用像

这样的正则表达式分割搜索字符串中的单词
searchString.split(/\W/);

并对结果数组中的每个单词进行 OR 搜索。

更新fiddle

var searchStrings = str_needle.split(/\W/);

for (var i = 0, len = searchStrings.length; i < len; i++) {
    var currentSearch = searchStrings[i].toUpperCase();
    if (currentSearch !== "") {
        nameDivs = document.getElementsByClassName("name");
        for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
            if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
                nameDivs[j].style.display = "block";
            }
        }
    }
}

【讨论】:

  • 啊,太棒了!这么简单的解决方法,谢谢!我什至可能会去掉“onKeyUp”功能以改善用户体验,这样所有结果都不会随着每个新词的开头再次显示 谢谢!
  • 我想投票但不想破坏你的 666 声誉:>
【解决方案2】:

另一种方法如下:

function gid(a_id) {
  return document.getElementById(a_id);
}

function close_all() {

  // applies the Array.prototype.forEach() method to the array-like nodeList
  // returned by document.querySelectorAll() (the string passed to which finds all
  // elements with an id that starts with ('^=') the string 'user_':
  [].forEach.call(document.querySelectorAll('[id^=user_]'), function(div) {
    // 'div' is the array element (the node) itself:
    div.style.display = 'none';
  });

}


function find_my_div() {
  close_all();

  // getting the trimmed lower-cased string from the input element, split
  // on white-space characters to create an array:
  var keywords = gid('edit_search').value.trim().toLowerCase().split(/\s+/),
    // as above, selecting all elements whose id starts with the string 'user_':
    haystack = document.querySelectorAll('[id^="user_"]'),
    // working out whether text is accessed by node.textContent, or node.innerText:
    textProp = 'textContent' in document.body ? 'textContent' : 'innerText',
    // an initialised variable, for later:
    userWords,

    // filters the haystack (the divs whose id starts with 'user_'):
    found = [].filter.call(haystack, function(user) {
      // assigns the lower-cased string to the created-variable:
      userWords = user[textProp].toLowerCase();
      // returns those div elements whose text contains some of
      // the words returned, earlier, as the keywords:
      return keywords.some(function (word) {
        return userWords.indexOf(word) > -1;
      });
    });

  // iterates over the found elements, and shows them:
  [].forEach.call(found, function(user) {
    user.style.display = 'block';
  });

}

<body>
  <input type="text" id="edit_search" onkeyup="javascript: find_my_div();">
  <input type="button" onClick="javascript: find_my_div();" value="Find">

  <script>
    function gid(a_id) {
      return document.getElementById(a_id);
    }

    function close_all() {

      [].forEach.call(document.querySelectorAll('[id^=user_]'), function(div) {
        div.style.display = 'none';
      });

    }


    function find_my_div() {
      close_all();
      var keywords = gid('edit_search').value.trim().toLowerCase().split(/\s+/),
        haystack = document.querySelectorAll('[id^="user_"]'),
        textProp = 'textContent' in document.body ? 'textContent' : 'innerText',
        userWords,
        found = [].filter.call(haystack, function(user) {
          userWords = user[textProp].toLowerCase();
          return keywords.some(function (word) {
            return userWords.indexOf(word) > -1;
          });
        });
      console.log(found);
      [].forEach.call(found, function(user) {
        user.style.display = 'block';
      });

    }
  </script>

  <div id="user_0" style="display:none">Andy Daulton
    <br/>Owner Nissan
    <br/>
    <br/>
  </div>
  <div id="user_1" style="display:none">Doug Guy
    <br/>Bug Collector
    <br/>
    <br/>
  </div>
  <div id="user_2" style="display:none">Sam Hilton
    <br/>Famous Celebrity in Hollywood
    <br/>
    <br/>
  </div>
  <div id="user_3" style="display:none">Don Grey
    <br/>Old man
    <br/>
    <br/>
  </div>
  <div id="user_4" style="display:none">Amy Hinterly
    <br/>Cook
    <br/>
    <br/>
  </div>
  <div id="user_5" style="display:none">Gary Doll
    <br/>Racecar Driver
    <br/>
    <br/>
  </div>
  <div id="user_6" style="display:none">Tod Akers
    <br/>Football Player
    <br/>
    <br/>
  </div>
  <div id="user_7" style="display:none">Greg Barkley
    <br/>Interior designer
    <br/>
    <br/>
  </div>
  <div id="user_8" style="display:none">Alen Simmons
    <br/>8th place winner
    <br/>
    <br/>
  </div>

参考资料:

【讨论】:

  • 这不适用于给定的用例,即“mr guy”不返回任何结果。
  • @Matt:是的,是的……(嗯,现在无论如何……)谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2015-05-05
相关资源
最近更新 更多