'temp'라는 여러 배열을 포함해야하는 외부 JS 배열 'main_category'가 있습니다.
배열 temp에는 li 태그에서 가져온 여러 문자열 요소가 포함됩니다.
두 배열을 모두 채우기 위해 아래와 같이 html 페이지의 각 ul 태그에 대해 각 li 태그를 통해 for 루프를 실행하고 있습니다.
function a{
var category_list = [];
var temp;
//how to split this list iteration into two for-loops
$(".ul_list li").each(function(){
temp = [];
//adding only those list elements of a ul, that are red in color
if($(this).attr("style") == "color:red"){
var cat = $(this).text();
cat = cat.replace(/\s\s+/g, ' '); //removes whitespaces
temp.push(cat); //creates a single array for a single element
}
}
category_list.push(temp);
});
}
원하는 출력 :
category_list = [['l1', 'l2', 'l3'], ['l1', 'l2', 'l3'], ['l1', 'l2', 'l3']..]
전류 출력 :
category_list = [['li'], ['l2'], ['l3']...]
그러나 temp.push (cat) LOC는 하나의 ul 내의 모든 li 요소에 대해 temp = []를 만드는 대신 각 개별 li 요소에 대한 임시 배열을 만듭니다.
각 .ul_list
요소 를 반복하여이 작업을 수행 할 수 있으며 해당 순서의 자식이 예상 한 결과를 제공해야합니다.
function a() {
let list = []
$(".ul_list").each(function() {
let temp = []
$(this).children().each(function() {
let text = $(this).text()
text.replace(/\s\s+/g, ' ')
temp.push(text)
})
list.push(temp)
})
return list
}
console.log(a())
또는 중첩 된를 ul
서로 내부에서 처리 할 수있는 재귀 구현이 필요한 경우 :
function getListItems(ul) {
let temp = []
$(ul).children().each(function() {
if ($(this).is("ul")) { // checks if child is a list
temp.push(getListItems($(this))) // recursive call
} else { // child is list item
let text = $(this).text()
text.replace(/\s\s+/g, ' ')
temp.push(text)
}
})
return temp
}
function a() { // main function
let list = []
$(".ul_list").each(function() {
list.push(getListItems($(this)))
})
return list
}
console.log(a())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src=https://code.jquery.com/jquery-1.9.1.js></script>
</head>
<body>
<ul class="ul_list">
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
</ul>
</ul>
</ul>
<ul class="ul_list">
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
</ul>
</ul>
</ul>
</ul>
<ul class="ul_list">
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
<ul class="ul_list">
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
<ul class="ul_list">
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다