根据 class 使用 table 中的值填充数组

Populating an array with values in a table based on the class

我在 table 中有一个名称列表,所有名称都使用 html 赋予相同的 class。如何用列表中的所有名称填充一个数组?此外,如何打印出该数组?这可以用 .each 函数完成吗?

听起来你需要 jquery .each

看这里:http://api.jquery.com/jquery.each/

会是这样的

var array = [];
$(".class").each(function() {
    array.push($(this).html());
});

假设您的 HTML 结构与此类似:

<table>
    <tr>
        <td class="name">Jim</td>
        ...
    </tr>
    ...
</table>

以下 javascript (vanilla js) 将检索您想要的 DOM 节点并将值放入数组中:

//create our names array
var namesArray = [];

//fetch our names data when the DOM is fully loaded
document.addEventListener("DOMContentLoaded", function(event) {
    //fetch all elements in DOM with 'name' class
    var nameElements = document.getElementsByClassName('name');

    //get the text contents of each DOM element in the nameElements array and assign it into the namesArray
    for (i = 0; i < nameElements.length; i++) {
        namesArray.push(nameElements[i].innerHTML);
    }

    //do something with the names array
    console.log(namesArray);
});

JSFIDDLE DEMO

这是构建数组的方式:

var myArray = [];

$(".myclass").each(function() {
    myArray[myArray.length] = $(this).text();
});

这是打印数组的方式:

for (var i = 0; i < myArray.length; i++) {
    console.log(myArray[i]); //prints to the console
}