jQuery를 사용하여 입력할 때 목록 필터링
간단한 데이터베이스 쿼리를 사용하여 웹 응용 프로그램의 사용자 목록을 순서대로 작성할 계획이었지만, 원하는 사용자의 이름을 텍스트 입력에 입력하여 이 목록을 필터링할 계획입니다.
jQuery를 사용하여 입력 상자의 문자열을 목록 항목 중 하나에 일치시킨 후 일치하는 문자열이 포함된 항목에 새 클래스를 동적으로 적용하고 해당 클래스를 포함하지 않는 다른 모든 항목을 숨김으로써 다른 항목을 숨깁니다.
이걸 할 수 있는 좋은 방법을 아는 사람?
이 경우,ul
가 있다id
의theList
, 다음과 같은 방법이 있습니다.
<input type="text" onkeyup="filter(this)" />
<script language="javascript" type="text/javascript">
function filter(element) {
var value = $(element).val();
$("#theList > li").each(function() {
if ($(this).text().search(value) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
}
</script>
대소문자를 구분하는 필터를 사용하지 않으려면.toLowerCase()
다음과 같은 행으로 이동합니다.
var value = $(element).val().toLowerCase();
if ($(this).text().toLowerCase().search(value) > -1)
또는 Marrek Tihkan이 투고한 내용을 바탕으로 한 보다 간결한 버전을 위해 each() 루프를 다음과 같이 대체할 수 있습니다.이것이 더 나은지 나쁜지 확실하지 않다.
$('#theList > li:not(:contains(' + value + '))').hide();
$('#theList > li:contains(' + value + ')').show();
Nikolas가 Marrek의 솔루션과 조합한 솔루션은 입력 텍스트가 비어 있으면 오차를 일으킨다.
다음 솔루션은 이 문제를 수정하고 'a' 태그로 둘러싸인 목록에서 작동합니다.
이 함수는 첫 글자가 대문자로 표시된 단어(예: 이름)로 요소를 필터링하도록 설계되었습니다.필터링 순서는 다음과 같습니다.'An' 또는 'an'을 입력하면 목록의 모든 요소가 해당 문자로 시작됩니다(예: Anthony는 일치하지만 Fanny는 일치하지 않습니다).
function filter (element,what) {
var value = $(element).val();
value = value.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
if (value == '') {
$(what+' > a > li').show();
}
else {
$(what + ' > a > li:not(:contains(' + value + '))').hide();
$(what + ' > a > li:contains(' + value + ')').show();
}
};
다음으로 스크립트로 동작하는HTML 코드의 예를 나타냅니다.
<input type="text" onkeyup="filter(this,'theList')" />
<ul id="theList">
<li><a href="">Tyrone Schlecht</a></li>
<li><a href="">Javier Ress</a></li>
<li><a href="">Carlene Tomes</a></li>
<li><a href="">Neil Aigner</a></li>
<li><a href="">Nita Schreffler</a></li>
<li><a href="">Clinton Knuckles</a></li>
<li><a href="">Eve Kellett</a></li>
<li><a href="">Jamie Kaspar</a></li>
<li><a href="">Emilia Hooton</a></li>
<li><a href="">Kenya Sidney</a></li>
</ul>
나는 그것들을 모두 반복하여 마녀가 일치하지 않는 것을 숨기고 일치하는 것을 보여 주었다.
$('li').hide();
$('li:contains(' + needle + ')').show();
John Resig에 의해 php에서 jQuery로 이식된 LiveQuery를 사용할 수 있습니다.
주의: PHP 메서드의 Quicksilver 메서드에 의존하며, 이는 Joshaven과 Joshaven에 의해 JavaScript로 포팅되었습니다.
사용 예:
$("#text_box_selector").liveUpdate("#list_selector");
주의:#list_selector
다음을 포함하는 요소를 찾아야 합니다.li
요소들
플러그인 + 정렬 + 라이브 데모
// https://github.com/joshaven/string_score
String.prototype.score = function (word, fuzziness) {
'use strict';
// If the string is equal to the word, perfect match.
if (this === word) { return 1; }
//if it's not a perfect match and is empty return 0
if (word === "") { return 0; }
var runningScore = 0,
charScore,
finalScore,
string = this,
lString = string.toLowerCase(),
strLength = string.length,
lWord = word.toLowerCase(),
wordLength = word.length,
idxOf,
startAt = 0,
fuzzies = 1,
fuzzyFactor,
i;
// Cache fuzzyFactor for speed increase
if (fuzziness) { fuzzyFactor = 1 - fuzziness; }
// Walk through word and add up scores.
// Code duplication occurs to prevent checking fuzziness inside for loop
if (fuzziness) {
for (i = 0; i < wordLength; i+=1) {
// Find next first case-insensitive match of a character.
idxOf = lString.indexOf(lWord[i], startAt);
if (idxOf === -1) {
fuzzies += fuzzyFactor;
} else {
if (startAt === idxOf) {
// Consecutive letter & start-of-string Bonus
charScore = 0.7;
} else {
charScore = 0.1;
// Acronym Bonus
// Weighing Logic: Typing the first character of an acronym is as if you
// preceded it with two perfect character matches.
if (string[idxOf - 1] === ' ') { charScore += 0.8; }
}
// Same case bonus.
if (string[idxOf] === word[i]) { charScore += 0.1; }
// Update scores and startAt position for next round of indexOf
runningScore += charScore;
startAt = idxOf + 1;
}
}
} else {
for (i = 0; i < wordLength; i+=1) {
idxOf = lString.indexOf(lWord[i], startAt);
if (-1 === idxOf) { return 0; }
if (startAt === idxOf) {
charScore = 0.7;
} else {
charScore = 0.1;
if (string[idxOf - 1] === ' ') { charScore += 0.8; }
}
if (string[idxOf] === word[i]) { charScore += 0.1; }
runningScore += charScore;
startAt = idxOf + 1;
}
}
// Reduce penalty for longer strings.
finalScore = 0.5 * (runningScore / strLength + runningScore / wordLength) / fuzzies;
if ((lWord[0] === lString[0]) && (finalScore < 0.85)) {
finalScore += 0.15;
}
return finalScore;
};
// http://ejohn.org/apps/livesearch/jquery.livesearch.js
jQuery.fn.liveUpdate = function(list) {
list = jQuery(list);
if (list.length) {
var rows = list.children('li'),
cache = rows.map(function() {
return this.innerHTML.toLowerCase();
});
this
.keyup(filter).keyup()
.parents('form').submit(function() {
return false;
});
}
return this;
function filter() {
var term = jQuery.trim(jQuery(this).val().toLowerCase()),
scores = [];
if (!term) {
rows.show();
} else {
rows.hide();
cache.each(function(i) {
var score = this.score(term);
if (score > 0) {
scores.push([score, i]);
}
});
jQuery.each(scores.sort(function(a, b) {
return b[0] - a[0];
}), function() {
jQuery(rows[this[1]]).show();
});
}
}
};
$("#search").liveUpdate("#colors");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="search"><br/>
<ul id="colors">
<li>Cat Book</li>
<li>Dog Basket</li>
<li>Bear Cub</li>
<li>Car Door</li>
<li>Another option</li>
<li>Another Animal</li>
</ul>
// Just a shorter version
$('ul>li').hide().has(':contains(' + needle + ')').show();
// case insensitive searching with animation
$("ul>li").slideUp().filter( function() {
return $(this).text().toLowerCase().indexOf(needle) > -1
}).stop(true).fadeIn();
이 W3의 예에서 영감을 얻어 대체적이고 컴팩트한 솔루션을 개발했습니다.
이 예에서는 링크된 세 가지 옵션을 볼 수 있습니다.
- UL 항목만 필터링
- 임의의 항목 필터링
- CSS 애니메이션 효과로 항목 필터링
JS 코드에서는 JS를 사용하다. JS 코드를 하면 어떤 수 있습니다.$("#anyItemList *")
★★★★★★★★★★★★★★★★★★:
$("#anyItemListInputFilter").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#anyItemList *").filter(function() {
let item = $(this).text().toLowerCase().indexOf(value) > -1;
$(this).toggle(item);
});
});
이 하하음음음 음음음음 음음 for for for for for for for for for for에 한하는 UL
그 는 「」, 「」로 변경할 수 .$("#ulList li")
) (예시로)
css 애니메이션 효과도 추가할 경우 몇 가지 제약사항이 있습니다.
- 정의된 " " " 필요" 필요
max-height
px
큰 큰 overflow-y:hidden;
그래서 나는 다음과 같이 선언할 수밖에 없었다.
#anyItemAnimatedList * {
transition:all 0.5s ease;
opacity:1;
max-height:500px;
overflow-y:hidden;
}
#anyItemAnimatedList ul {
list-style-position:inside;
}
#anyItemAnimatedList .hidden {
max-height:0;
opacity:0;
border:0;
}
는 은신하다, 하다, 하다.opacity
★★★★★★★★★★★★★★★★★」max-height
트랜지션 및 " " "border:0
이 합니다.button
기본 브라우저 스타일을 태그합니다.
「」의 는, 「」입니다.OL
★★★★★★★★★★★★★★★★★」UL
는, 「목록」을 설정하기 위해서 합니다.list-style-position:inside;
에 의해 디폴트 Firefox Chrome의 .list-style-position:outside
.
Firefox의 경우 2003년 이후 이미 알려진 버그입니다.크롬도 마찬가지입니다.
언급URL : https://stackoverflow.com/questions/1772035/filtering-a-list-as-you-type-with-jquery
'programing' 카테고리의 다른 글
Woocommerce에서 적용된 할인 쿠폰을 프로그래밍 방식으로 제거하는 방법은 무엇입니까? (0) | 2023.03.11 |
---|---|
템플릿 없이 Django에서 빈 응답을 보내려면 어떻게 해야 합니까? (0) | 2023.03.11 |
WordPress TinyMCE wp_editor()를 사용할 때 자리 표시자 텍스트를 설정하는 방법 (0) | 2023.03.11 |
Spring 및 Jackson의 완전한 데이터 바인딩을 통한 REST (0) | 2023.03.11 |
UNION with WHERE 조항 (0) | 2023.03.11 |