我们可以使用 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.com/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>
使用 jqueryeach() 方法jquery 中的each() 方法用于迭代数组、对象和所有可迭代项。要使用 jquery 转换数组中的元素列表,我们遵循下面给出的步骤
使用 $(“ul li”) 选择所有列表项
创建一个空数组来存储列表项
使用each()方法循环遍历所有选定的项目
在每次迭代中,当前列表项的innertext都会被推入“items”数组中。
将列表项显示到浏览器。
示例在此示例中,我们使用 jquery 的 $.each( ) 方法将元素列表转换为数组。
<html><head> <script src=https://ajax.googleapis.com/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>
以上就是如何使用 jquery 转换数组中的元素列表?的详细内容。
