我有一个如下所示的html结构:
<table class="assignments-table">
<tr class="assignment-row">
<td class="100175">100175</td>
<td>...</td>
<td>...</td>
</tr>
<tr class="assignment-row">
<td class="100175">100175</td>
<td>...</td>
<td>...</td>
</tr>
<tr class="assignment-row">
<td class="100175">100175</td>
<td>...</td>
<td>...</td>
</tr>
<tr class="assignment-row">
<td class="100176">100176</td>
<td>...</td>
<td>...</td>
</tr>
<tr class="assignment-row">
<td class="100177">100177</td>
<td>...</td>
<td>...</td>
</tr>
</table>
我想使用jQuery找到所有具有相同类的td元素(这些是上面示例中的td class =“100175”。)
到目前为止,我的jQuery代码如下所示:
$(document).ready(function() {
$(".assignment-row td:nth-child(1)").each(function() {
if( $(this).length > 1) {
console.log('more than one elements with same class exist');
$(this).addClass('same');
// do other stuff too
} else {
console.log('no elements with the same class exist');
}
});
上述代码未通过条件检查并进入else。
我也试过修改我的jQuery:
$(".assignments-table tr").each(function() {
var t = $(this).find("td:nth-child(1)");
if($(t).length){
console.log('more than one elements with same class exist');
$(t).addClass('same');
// do other stuff too
} else {
console.log('no elements with same class exist')
};
});
这也是错误的,因为它继续并将class =“same”添加到所有:nth-child(1)元素,即使它们没有相同的类。
重要提示:这些数字是动态生成的,所以我不能直接将这些数字用作选择器。
我的错误在哪里?
谢谢。
答案 0 :(得分:0)
我已创建此fiddle并更正了您的代码。我想我做了你想做的事。
基本上,对于每一行,我得到了td export default {
data: function () {
return {
username: '',
password: '',
users: []
}
},
methods: {
login: function() {
Vue.http.get('/api/users/all').then((response) => {
console.log("SUCCESS",response);
this.users = response.body;
console.log(users);
}, function (error) {
console.log("Error", error.status); // handle error
});
}
}
};
,并在表格中通过parent()进行了验证,以检查是否有更多行具有相同的class
。
您的代码存在以下问题:
class
和
$(".assignment-row td:nth-child(1)").each(function() {
if( $(this).length > 1) { // You were checking for the length of the current td instead of the length for td's with the same class
console.log('more than one elements with same class exist');
$(this).addClass('same');
// do other stuff too
} else {
console.log('no elements with the same class exist');
}
});
如果您不理解我的解释,请告诉我!