How to do a case insensitive search for text within elements using jQuery
我有以下基本布局:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <ul id="ul-1"> <li id="li-1-1" class="li"> </li> <li id="li-1-2" class="li"> </li> </ul> <ul id="ul-2"> <li id="li-2-2" class="li"> </li> </ul> <ul id="ul-3"> <li id="li-3-1" class="li"> </li> <li id="li-3-2" class="li"> </li> <li id="li-3-3" class="li"> </li> <li id="li-3-4" class="li"> </li> </ul> |
我要做的是,当输入字段被输入时,它会启动对
到目前为止,我有以下几点:
1 2 3 4 5 6 7 8 9 10 11 12 | $('#my-input').keyup(function(e) { e.stopImmediatePropagation(); var keycode = ( e.keyCode ? e.keyCode : e.which ); if( keycode == 13 ) { //Do something } else { if( $('#my-input').val().length >= 3 ) { //code goes here } } )} |
最好的方法是什么?我已经研究过包含、过滤、以各种方式循环所有
这个怎么样?
HTML部分因测试目的而更改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <input id="my-input"/> <ul id="ul-1"> <li id="li-1-1" class="li"><p> This is something wonderful </p> </li> <li id="li-1-2" class="li"><span>Try is out</span> </li> </ul> <ul id="ul-2"> <li id="li-2-2" class="li">This needs to be selected </li> </ul> <ul id="ul-3"> <li id="li-3-1" class="li">No that wonderful </li> <li id="li-3-2" class="li">How is this? </li> <li id="li-3-3" class="li">Need to match </li> <li id="li-3-4" class="li">No need to match? </li> </ul> |
jquery/javascript
$("document").ready(函数()。{
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | $('#my-input').keyup(function(e) { e.stopImmediatePropagation(); var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == 13) { //Do something } else { var matchText = $('#my-input').val(); if (matchText.length >= 3) { var selectedLists = new Array(); var flagArray = new Array(); var i = 0; $(matchText.split(/\s+/)).each(function() { var textToMatch = $(this)[0]; if (textToMatch && textToMatch !="") { $("li").each(function() { if ($(this).html().match(eval("/" + textToMatch +"/ig"))) { if (!flagArray[$(this).attr("id")]) { selectedLists[i++] = $(this).attr("id"); //For your implementation, I suggest that you store the object, rather than the id so that you can clone it without an iteration flagArray[$(this).attr("id")] = true; } } }); } }); if (selectedLists.length > 0) { alert(selectedLists); } } } }); |
(});