我有一堆html元素,我想检索一些元素并将其放入数组中,这样我就可以在需要时检索它们。问题是我使用的jquery选择器无法正常工作,代码似乎还可以,我不知道为什么我要面对这些问题。有人可以帮我吗?请运行代码段
function grabData(){
//trying to get all h5 tags into an array
var count = $(".section").length;
var questquest =[];
for(i=0;i<count;i++){
questquest[i] = $('.section h5').eq(i).val();
console.log("questions = "+questquest[i]);
}
//trying to get all p tags into an array
var count = $(".section p").length;
var questP =[];
for(i=0;i<count;i++){
questP[i] = $('.section p').eq(i).val();
console.log("Items = "+questP[i]);
}
}
grabData();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="divider"></div>
<div class="section">
<h5>Section 1</h5>
<p>Stuff1</p>
<p>Stuff2</p>
<p>Stuff3</p>
<p>Stuff4</p>
</div>
<div class="divider"></div>
<div class="section">
<h5>Section 2</h5>
<p>Stuff1</p>
<p>Stuff2</p>
<p>Stuff3</p>
<p>Stuff4</p>
</div>
<div class="divider"></div>
<div class="section">
<h5>Section 3</h5>
<p>Stuff1</p>
<p>Stuff2</p>
<p>Stuff3</p>
<p>Stuff4</p>
</div>
</body>
</html>
我正在尝试将所有p以及h5都放入数组。
答案 0 :(得分:0)
您需要使用questquest.push($('.section h5').eq(i).text());
和questP.push($('.section p').eq(i).text());
。您可以避免使用questquest[i]
进行赋值,因为push()
用于将新值添加到数组中,并且由于在您的情况下该序列是连续的,因此请使用push()
。
此外,对于元素h5
和p
,请使用text()
函数而不是val()
来获取元素的内容。
function grabData(){
//trying to get all h5 tags into an array
var count = $(".section").length;
var questquest =[];
for(i=0;i<count;i++){
questquest.push($('.section h5').eq(i).text());
console.log("questions = "+ questquest[i]);
}
//trying to get all p tags into an array
var count = $(".section p").length;
var questP =[];
for(i=0;i<count;i++){
questP.push($('.section p').eq(i).text());
console.log("Items = "+questP[i]);
}
}
grabData();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="divider"></div>
<div class="section">
<h5>Section 1</h5>
<p>Stuff1</p>
<p>Stuff2</p>
<p>Stuff3</p>
<p>Stuff4</p>
</div>
<div class="divider"></div>
<div class="section">
<h5>Section 2</h5>
<p>Stuff1</p>
<p>Stuff2</p>
<p>Stuff3</p>
<p>Stuff4</p>
</div>
<div class="divider"></div>
<div class="section">
<h5>Section 3</h5>
<p>Stuff1</p>
<p>Stuff2</p>
<p>Stuff3</p>
<p>Stuff4</p>
</div>
</body>
</html>