我正在循环访问几个如下所示的 HTML 实例:
<div class="matchup-container">
<div class="gamequestion">
<strong>NBA: Who will WIN this matchup?</strong>
</div>
<table class="mg-gametableQ">
<tbody>
<tr>
<td class="mg-column1 start">
<div class="matchupDate">
<span class="startTime">11:00 AM</span>
</div>
</td>
<td class="mg-column3 opponents ">
<span>
<strong>
<a>Team</a>: Win
</strong>
</span>
</td>
</tr>
<tr>
<td class="mg-column1 start">
<div class="matchupDate">
<span class="startTime">11:00 AM</span>
</div>
</td>
<td class="mg-column3 opponents ">
<span>
<strong>
<a>Team</a>: Win
</strong>
</span>
</td>
</tr>
</tbody>
</table>
</div>
有几个matchup-container
div 进行循环,所以我使用 .each()
要做到这一点。然后我想循环遍历每个 mg-column3
在该 div 内,所以我使用 .each()
再次。最后,我想将 <a>
内的文本拉出(在本例中为“团队”),并将其附加到 mg-column3
内分区我的 jQuery 代码在这里:
$('.matchup-container').each(function() {
var title = $.trim($(this).find('.gamequestion').text());
$(this).find('.mg-column3').each(function () {
if (isStraightUp(title))
{
var teams = getStraightUpTeams(this);
$(this).append('<span class=odds-favorite>' + teams[0] + '</span>');
}
});
});
function isStraightUp (title)
{
return true;
}
function getStraightUpTeams(matchup)
{
var teams = [];
teams[0] = $(matchup).find("a")[0].text();
teams[1] = $(matchup).find("a")[1].text();
return teams;
}
但是什么也没发生。 Chrome 开发工具告诉我无法调用 .text()
在未定义的元素上,所以一切都会崩溃。但我不明白为什么 jQuery 没有抓取 <a>
内的文本。我想要的标签。这是 JSFiddle.有人可以帮忙吗?
最佳答案
由于 $(matchup)
返回一个 jQuery 对象,因此您需要使用 jQuery 方法,如 .eq() 或 :eq() 选择器:
teams[0] = $(matchup).find("a").eq(0).text();
teams[1] = $(matchup).find("a").eq(1).text();
<强> Updated Fiddle
或者:
teams[0] = $(matchup).find("a:eq(0)").text();
teams[1] = $(matchup).find("a:eq(1)").text();
<强> Updated Fiddle
关于javascript - jQuery 似乎没有找到嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22469679/