반응형
jQuery : 목록 요소의 수를 세시겠습니까?
jQuery로 추가 항목을 추가하기 전에 일부 서버 측 코드에서 생성 된 목록이 있습니다. 이미 몇 개의 항목이 이미 있는지 파악해야합니다.
<ul id="mylist">
<li>Element 1</li>
<li>Element 2</li>
</ul>
시험:
$("#mylist li").length
궁금한 점이 있습니다. 왜 크기를 알아야합니까? 당신은 단지 사용할 수 없습니다 :
$("#mylist").append("<li>New list item</li>");
?
var listItems = $("#myList").children();
var count = listItems.length;
물론 당신은 이것을 응축 할 수 있습니다
var count = $("#myList").children().length;
jQuery에 대한 자세한 도움말을 보려면 http://docs.jquery.com/Main_Page 를 시작하는 것이 좋습니다.
.size () 메서드 또는 .length 속성을 호출 할 때 동일한 결과가 발생하지만 .length 속성은 함수 호출의 오버 헤드가 없으므로 선호됩니다. 가장 좋은 방법은 다음과 같습니다.
$("#mylist li").length
나는 이것이해야한다고 생각한다.
var ct = $('#mylist').children().size();
물론 다음과 같습니다.
var count = $("#myList").children().length;
다음과 같이 요약 될 수 있습니다 (변수를 설정할 필요가없는 'var'을 제거하여)
count = $("#myList").children().length;
그러나 이것은 더 깨끗합니다.
count = $("#mylist li").size();
시험
$("#mylist").children().length
목록 요소 수
alert($("#mylist > li").length);
리스트 요소의 수를 세는 또 다른 방법 :
var num = $("#mylist").find("li").length;
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="mylist">
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
<li>Element 5</li>
</ul>
$("button").click(function(){
alert($("li").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Count the number of specific elements</title>
</head>
<body>
<ul>
<li>List - 1</li>
<li>List - 2</li>
<li>List - 3</li>
</ul>
<button>Display the number of li elements</button>
</body>
</html>
참고 URL : https://stackoverflow.com/questions/605969/jquery-count-number-of-list-elements
반응형
'Programing' 카테고리의 다른 글
HTML 문서의 문자 인코딩이 선언되지 않았습니다 (0) | 2020.06.26 |
---|---|
키 저장소 정보를 build.gradle에 넣지 않고 APK에 서명 (0) | 2020.06.26 |
팬더에서 데이터 프레임의 처음 세 행을 삭제하십시오. (0) | 2020.06.26 |
getOne 및 findOne 메소드를 사용하는 경우 Spring Data JPA (0) | 2020.06.26 |
mysql에서 문자열을 날짜로 변환하는 방법은 무엇입니까? (0) | 2020.06.26 |