我试图获取 .lists
类中 .list
类的每个 div 的文本,并从 .lineone
获取文本类(class)。在下面的示例中,它是“Reilly Lawless”
<div class="lists">
<div class="list history0" id="history0">
<div class="info">
<a href="/user/reillylawless23"><a href="/user/reillylawless23">
<a href="/user/reillylawless23">
<div class="picture monophoto">
<div class="text" style="font-size: 34px; margin-top: 4.125px;">RJL</div>
<div class="img" style="background-image: url();"></div>
</div>
</a>
</a></a>
<div class="right">
<a class="removelinkdefault" href="/user/reillylawless23"><a class="removelinkdefault" href="/user/reillylawless23">
<a class="removelinkdefault" href="/user/reillylawless23">
<div class="lineone">Reilly Lawless</div>
</a>
</a></a>
<div class="linetwo">reillylawless23's List</div>
</div>
</div>
<a href="/user/reillylawless23"><a href="/user/reillylawless23">
<a href="/user/reillylawless23">
<div class="boxes">
<div class="left">
<div class="box box1" style="background-image: url("http://s3.amazonaws.com/22hints/hints/55b10e3610cd68.77289350.jpg");"></div>
</div>
<div class="right">
<div class="box box2" style="background-image: url("http://s3.amazonaws.com/22hints/hints/55ca535e973368.44212514.jpg");"></div>
<div class="box box3" style="background-image: url("http://secondglobe.com/wp-content/uploads/2013/10/Miraculous-Lake-Carrera-in-Buenos-Aires-3.jpg");"></div>
</div>
</div>
</a>
</a></a>
<a class="cbutton whiteonblack" href="/user/reillylawless23">
VIEW LIST<!--SEE <span class="owner">JOHN'S</span>-->
</a>
</div>
<!-- then <div class="list history1" id="history1"> and so on -->
</div>
这是我通过 jQuery 获取它的尝试:
$(".lists .list").each(function(index) {
//this returns all of the text for all of .lineone each time
var hint_name = $('.lineone').text();
//this returns nothing
var hint_name = $(this).children('.lineone').text();
});
我做错了什么以及如何解决它?
最佳答案
您的选择器缺少.lineone
。从那里,您可以在 each
处理函数中使用 this
关键字来引用迭代中的当前元素。试试这个:
$(".lists .list .lineone").each(function(index) {
var text = $(this).text();
// do something with the text here...
});
如果您有意遍历每个 .list
并希望在其中查找 .lineone
,则需要使用 find()
as children()
仅搜索直接后代:
$(".lists .list").each(function(index) {
var text = $(this).find('.lineone').text();
// do something with the text here...
});
关于javascript - 遍历类中的所有 div 并从特定元素获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929506/