在 jQuery 中,可以使用 $.each() 方法来遍历多维数组。以下是一个示例:
<!DOCTYPE html><html><head> <title>jQuery foreach 遍历多维数组</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><ul id="nested-list"> <li>Item 1</li> <li> Item 2 <ul> <li>Subitem 1</li> <li>Subitem 2</li> </ul> </li> <li>Item 3</li></ul><script>$(document).ready(function(){ var nestedList = []; $('#nested-list li').each(function(){ var item = {}; item.text = $(this).text(); if ($(this).find('ul').length > 0) { item.subitEMS = []; $(this).find('ul li').each(function(){ item.subitems.push($(this).text()); }); } nestedList.push(item); }); $.each(nestedList, function(index, value){ console.log('Item: ' + value.text); if (value.subitems) { $.each(value.subitems, function(index, subitem){ console.log('Subitem: ' + subitem); }); } });});</script></body></html>在上面的示例中,首先通过 $('#nested-list li').each() 方法遍历了多维数组中的每个元素,并将元素的文本内容存储在对象中。如果元素包含子元素,将子元素的文本内容也存储在对象中。然后使用 $.each() 方法遍历多维数组并输出每个元素的文本内容,如果元素包含子元素,则也输出子元素的文本内容。


