我有一张桌子
<table id='mytable'>
<tr>
<th> Cars </th>
<th> Food </th>
<th> clothes</th>
</tr>
<tr>
<td> 1 </td>
<td> yes </td>
<td> jeans </td>
</tr>
<tr>
<td> 1 </td>
<td> yes </td>
<td> jeans </td>
</tr>
<tr>
<td> 84 </td>
<td> no </td>
<td> shirt </td>
</tr>
<tr>
<td> 4984 </td>
<td> yes </td>
<td> hat </td>
</tr>
我有一个javascript函数,它接受第一个td并获取值,但在这种情况下它只取第一个值1.我想将所有第一列不同的值存储在一个数组中。所以最终的结果应该是
$firstColumnArray = [1,84, 4984]
我的功能看起来像
$(document).ready(function()
{
$one = document.getElementById("table");
$two = $(this).find("td").eq(0).text()
alert($two);
});
如何循环遍历表格的第一行内容并将其存储在变量中?
答案 0 :(得分:1)
您需要遍历所有行
beforeEach(function () {
protractor_1.browser.waitForAngularEnabled(true);
browser.get('http://127.0.0.1:8080') // set your url here
//Disable animations
protractor_1.browser.manage().addCookie({
name: 'disableAnimations',
value: 'true'
}, '/', '127.0.0.1');
});
然后过滤掉重复项。
let res = [];
$('#mytable tr').each(function() {
if(!$(this).find('td:first').length) return;
var customerId = $(this).find("td").eq(0).text();
res.push(customerId);
});
答案 1 :(得分:0)
您可以使用此选择器 "tr > td:first-child"
$(document).ready(function() {
var values = [];
$('#mytable').find("tr > td:first-child").each(function() {
var value = $(this).html().trim();
if (!values.includes(value))
values.push(value);
});
console.log(values);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='mytable'>
<tr>
<th> Cars </th>
<th> Food </th>
<th> clothes</th>
</tr>
<tr>
<td> 1 </td>
<td> yes </td>
<td> jeans </td>
</tr>
<tr>
<td> 1 </td>
<td> yes </td>
<td> jeans </td>
</tr>
<tr>
<td> 84 </td>
<td> no </td>
<td> shirt </td>
</tr>
<tr>
<td> 4984 </td>
<td> yes </td>
<td> hat </td>
</tr>
I have a javascript function that takes the first td and get the value, but it only takes the first value in this case 1. I want to take all of the first columns distinct values and store it in an array. so the end result should be
&#13;
答案 2 :(得分:0)
您可以使用includes数组方法迭代它们并排除属性..
$(document).ready(function()
{
var result = [];
$('table tr').each(function(){
if(!$(this).find('td:first').length) return;
var text = $(this).find('td:first').text();
if(!result.includes(text)){
result.push(text);
}
});
console.log(result);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='mytable'>
<tr>
<th> Cars </th>
<th> Food </th>
<th> clothes</th>
</tr>
<tr>
<td> 1 </td>
<td> yes </td>
<td> jeans </td>
</tr>
<tr>
<td> 1 </td>
<td> yes </td>
<td> jeans </td>
</tr>
<tr>
<td> 84 </td>
<td> no </td>
<td> shirt </td>
</tr>
<tr>
<td> 84 </td>
<td> no </td>
<td> shirt </td>
</tr>
<tr>
<td> 4984 </td>
<td> yes </td>
<td> hat </td>
</tr>
</table>
&#13;