我在表中有一个名称列表,所有名称都使用html给出了相同的类。如何使用列表中的所有名称填充数组?此外,我如何打印出该阵列?这可以用.each函数完成吗?
答案 0 :(得分:1)
听起来你需要jquery .each
请看这里:http://api.jquery.com/jquery.each/
就像这样
var array = [];
$(".class").each(function() {
array.push($(this).html());
});
答案 1 :(得分:1)
假设您的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 强>
答案 2 :(得分:1)
这是你构建数组的方法:
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
}