我有一张这样的表:
<div id="table">
<div class="header-row row">
<span class="cell primary">Team</span>
<span class="cell">GP</span>
<span class="cell">W</span>
</div>
<div class="row">
<input type="radio" name="expand">
<span class="cell primary" data-label="Team">Real Klarin</span>
<span class="cell" data-label="GP">1</span>
<span class="cell" data-label="W">0</span>
</div>
<div class="row">
<input type="radio" name="expand">
<span class="cell primary" data-label="Team">Cage</span>
<span class="cell" data-label="GP">5</span>
<span class="cell" data-label="W">4</span>
</div>
</div>
我的总体目标是打印(以迭代方式): 真正的克拉林 1 0 笼 五 4
所以,我尝试用这个开始收集所有跨度:
$('#table div span').each(function (index) {
console.log(this); // "this" is the current element in the loop
});
但它打印HTML对象和span
标签,让我感到困惑。有什么想法吗?
编辑:
console.log(this.textContent);
是一项改进,但现在我得到了: 球队 GP w ^ 真正的克拉林 ...
如何跳过第一个div?或者,换句话说,如何使用.header-row跳过div?
答案 0 :(得分:1)
你可以这样做:
$('.row:not(.header-row)').each(function(){
$(this).find('span').each(function(){
console.log($(this).text());
});
});
它正在做的是'对于不是标题行的每一行都这样做:' '对于此范围内的每个跨度,记录其文本(标记内的文本)
答案 1 :(得分:1)
试试这个。您正在记录DOM元素,而不是从jQuery包装的dom元素中提取的文本。
$('#table div span').each(function (index) {
console.log($(this).text());
});
或者代替嵌套循环,就像每个内部循环一样,您可以稍微改变您的选择策略。查看目标元素,我注意到一个具有自定义数据属性的公共线程(即data-label
);因此,你也可以这样选择:
// not selecting the header "cells"
$('#table [data-label]').each(function(i, el) {
console.log($(el).text());
})
这比在嵌套.each()
调用中选择和过滤dom更有效。
答案 2 :(得分:1)
要跳过第一个div,您需要{j}
中的:not
选择器或.not()
$('#table div:not(:first)').each(function (index) {
if(index == 1){ // index starts from 0 so for second record use 1
$(this).find('span').each(function(){
console.log($(this).text());
});
}
});
或
$('#table div').not(':first').find('span').each(function (index) {
console.log($(this).text());
});
答案 3 :(得分:0)
只需像这样使用.text()方法:
<script type="text/javascript">
$(function() {
$('#table div span').each(function() {
var text = $(this).text();
console.log(text);
});
});
</script>