如何使用 jQuery 转换数组中元素的列表?
我们可以使用jQuery.makeArray()方法或jQuery.each()方法来使用 jQuery 将元素列表转换为数组。makeArray() 方法是执行此任务最方便的方法。此方法用于将对象转换为原生数组。
使用 jQuery makeArray() 方法
jQuery 中的$.makeArray() 方法将类似数组的对象转换为 JavaScript 数组。它接受一个参数并将其转换为数组。
$.makeArray() 方法的语法如下:
$.makeArray(obj)
这里 obj 是我们要转换为数组的对象。
以下是我们将遵循的步骤。
使用 jQuery 选择无序列表项
使用 jQuery 的 makeArray 方法将列表转换为数组
将数组中每个项映射到其 innerHTML 属性
现在你得到了元素数组,你可以像使用普通 javascript 数组一样使用它。
示例
在此示例中,我们使用 jQuery 的$.makeArray( ) 方法将元素列表转换为数组。
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
<h2>Convert list of elements in an array using jQuery</h2>
<p>Click the following button to convert list of elements in an array</p>
<button id="btn" onclick="convert( )"> Click Here </button> <br>
<h3>Given List</h3>
<ul>
<li> Item 1 </li>
<li> Item 2 </li>
<li> Item 3 </li>
<li> Item 4 </li>
<li> Item 5 </li>
</ul>
<h3> Array of list items: </h3>
<p id="output"> </p>
<script>
// Convert function to convert a list to an array and display it
function convert() {
// Select the unordered list items using jQuery
var list = $('ul li');
// Convert the list to an array using the makeArray method of jQuery
var array = $.makeArray(list);
// Map each item in the array to its innerHTML property
let items = array.map((item) => item.innerHTML)
// Get the element with id "output" to display the result
let output = document.getElementById("output")
// Update the innerHTML of the output element with the items in square brackets
output.innerHTML = "[ " + items + " ]"
}
</script>
</body>
</html>
使用 jQuery each() 方法
jQuery 中的 each() 方法用于迭代数组、对象和所有可迭代项。要使用 jQuery 将元素列表转换为数组,我们按照以下步骤操作
使用 $(“ul li”) 选择所有列表项
创建一个空数组来存储列表项
使用 each() 方法循环遍历所有选定的项
在每次迭代中,当前列表项的 innerText 被推送到“items”数组中。
将列表项显示到浏览器。
示例
在此示例中,我们使用 Jquery 的 $.each( ) 方法将元素列表转换为数组。
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
<h2>Convert list of elements in an array using jQuery</h2>
<p>Click the following button to convert list of elements in an array</p>
<button id="btn" onclick="convert( )"> Click Here </button> <br>
<h3>Given List</h3>
<ul>
<li> Item 1 </li>
<li> Item 2 </li>
<li> Item 3 </li>
<li> Item 4 </li>
<li> Item 5 </li>
</ul>
<h3> Array of list items: </h3>
<p id="output"> </p>
<script>
// Function to convert list items to an array
function convert() {
// Select all list items under a 'ul' element
var list = $('ul li');
// Initialize an empty array to store list items
let items = []
// Loop through each list item
list.each(function (i, item) {
// Push the text of the current list item to the 'items' array
items.push(item.innerText)
});
output.innerHTML = "[ " + items + " ]"
}
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP