如何让jQuery将类应用于一行中的第一个td
我目前有一个表,它是数据库中结果的while循环。在我的表格行中,它包含一个值,该值将是+或-天数。我正在尝试创建一个jQuery脚本,它将发现td是否包含(“-”)或(“+”),我希望它将css样式应用于该行的第一个td。目前,它将其应用于所有行中的每个第一个td如何让jQuery将类应用于一行中的第一个td,jquery,Jquery,我目前有一个表,它是数据库中结果的while循环。在我的表格行中,它包含一个值,该值将是+或-天数。我正在尝试创建一个jQuery脚本,它将发现td是否包含(“-”)或(“+”),我希望它将css样式应用于该行的第一个td。目前,它将其应用于所有行中的每个第一个td $("tr td:nth-child(7):contains('+')").each(function() { $('tr td:first-child').css('background-color', '
$("tr td:nth-child(7):contains('+')").each(function() {
$('tr td:first-child').css('background-color', 'blue');
});
您需要使用$(this)
,以便在循环中引用“this”元素
然后,由于“this”是td
元素,因此找到父元素tr
,然后找到嵌套在该元素中的第一个子元素
$("tr td:nth-child(7):contains('+')").each(function() {
$(this).parent("tr").find('td:first-child').css('background-color', 'blue');
});
请参见演示:您需要使用$(this)
以便在循环中引用“this”元素
然后,由于“this”是td
元素,因此找到父元素tr
,然后找到嵌套在该元素中的第一个子元素
$("tr td:nth-child(7):contains('+')").each(function() {
$(this).parent("tr").find('td:first-child').css('background-color', 'blue');
});
请参阅演示:我会这样做
$(function(){
$("tr td:nth-child(7):contains('+')").each(function() {
// get a jQuery object of the selected element using `$(this)`
// then select `.siblings()`, and limit to first element in array (`.eq(0)`)
$(this).siblings().eq(0).css('background-color', 'blue');
});
});
小提琴:我会这样做
$(function(){
$("tr td:nth-child(7):contains('+')").each(function() {
// get a jQuery object of the selected element using `$(this)`
// then select `.siblings()`, and limit to first element in array (`.eq(0)`)
$(this).siblings().eq(0).css('background-color', 'blue');
});
});
Fiddle:@TheGambit没问题,如果这对你有帮助,请接受答案@没有问题,如果这对你有帮助,请接受答案。