我又回来了我的问题。
我正在尝试迭代jquery中的表。我的下面的代码,如果表有一个ID。但是,如果我的代码如下所示,将无法正常工作。
我只是试图将一个表作为目标,对其进行迭代,并找到一个带有“ price”类的跨度,该类中包含文本“ 8”。但是我首先在for循环中收到“无法读取未定义的属性'0'”错误。
这是我的代码。
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<table class="table">
<tr>
<td><span class="price">one</span></td>
<td><span class="price">two</span></td>
<td><span class="price">three</span></td>
<td><span>X</span></td>
</tr>
<tr>
<td><span>four</span></td>
<td><span>five</span></td>
<td><span>six</span></td>
<td><span>X</span></td>
</tr>
<tr>
<td><span>seven</span></td>
<td><span class="price">eight</span></td>
<td><span>nine</span></td>
<td><span>X</span></td>
</tr>
<tr>
<td><span>ten</span></td>
<td><span>eleven</span></td>
<td><span>twelve</span></td>
<td><span>X</span></td>
</tr>
</table>
<div id="dark">
<table class="table">
<tr>
<td><span class="price">one</span></td>
<td><span class="price">two</span></td>
<td><span class="price">three</span></td>
<td><span class="price">X</span></td>
</tr>
<tr>
<td><span class="price">four</span></td>
<td><span class="price">five</span></td>
<td><span class="price">six</span></td>
<td><span class="price">X</span></td>
</tr>
<tr>
<td><span class="price">seven</span></td>
<td><span class="price">eight</span></td>
<td><span class="price">nine</span></td>
<td><span class="price">X</span></td>
</tr>
<tr>
<td><span class="price">ten</span></td>
<td><span class="price">eleven</span></td>
<td><span class="price">twelve</span></td>
<td><span class="price">X</span></td>
</tr>
</table>
</div>
<script>
$(document).ready(function(){
var table = $('#dark').find('.table');
//console.log($(table).attr('class'));
for (var i = 0, row; row = $(table).rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var price = $(this).find('.price').text();
if(price == 'eight'){
$(this).find('.price').parent().next().addClass('removeMe');
}
}
}
});
</script>
<body>
</body>
答案 0 :(得分:2)
我认为您不需要重复任何操作。只需使用jquery选择器和过滤器功能即可。
$(document).ready(function() {
$('table td .price').filter(function() {
return $(this).text() == 'eight'
}).parent().next().addClass('removeMe');
});
答案 1 :(得分:1)
我认为您想在单元格上添加带有文本“八”的单元格后添加“ removeMe”类,因此此代码将起作用:
$('#dark').find('.table').find('td').each(function()
{
var price = $(this).find('.price').text();
if(price == 'eight')
{
$(this).next().addClass('removeMe');
}
});
我戴上JSFiddle。