简体   繁体   English

如果条件为真,则将类添加到父元素

[英]add class to parent element if conditions are true

I am trying to apply a class to a child's parent element if the conditions are true but cannot seem to get it to work. 我试图将一个类应用于子元素的父元素,如果条件为真但似乎无法使它工作。 In short, I want to check a table for a cell that is the number "0" and hide its parent row. 简而言之,我想检查一个表格中是否有一个数字为“0”的单元格并隐藏其父行。

I have created a basic jsfiddle of what I have done: http://jsfiddle.net/immbudden/YbZPE/3/ 我创建了一个基本的jsfiddle我所做的: http//jsfiddle.net/immbudden/YbZPE/3/

And the snippet of jquery that I have put together: 还有我放在一起的jquery片段:

if ($('#the_table>table>td:contains("0")').length === 1) {
    $(this).parent("tr").addClass("hidden");
}

I am still learning jQuery and javascript and this is probably something small, but I can't seem to put my finger on it! 我还在学习jQuery和javascript,这可能是小事,但我似乎无法把手指放在它上面!

Any help would be much obliged, thanks in advance! 任何帮助都有很大的帮助,提前谢谢!

$('td', '#the_table > table').each(function() {
    if ($(this).text() === '0') {
        $(this).parents("tr").addClass("hidden");
    }
});

FIDDLE 小提琴

Use your browser's developer tools! 使用浏览器的开发人员工具! Or Get Firebug . 或者获取Firebug

With that page loaded, try this in the javscript console: 加载该页面后,在javscript控制台中尝试:

$('#the_table>table>td:contains("0")')

If that gives you 如果这给了你

[ ]

then it's not finding any elements. 然后它没有找到任何元素。 Then you can try breaking it down, for example, see if this works: 然后你可以尝试将其分解,例如,看看是否有效:

$('#the_table>table>td')

And keep taking out and adding bits of that expression until it produces true or false as you require. 并继续取出并添加该表达式的位,直到它根据您的需要生成truefalse

you can do it like this, 你可以这样做,

$('#the_table table td').filter( function (index) {
    return $(this).text() == '0';
}).parent("tr").addClass("hidden");

http://jsfiddle.net/YbZPE/5/ http://jsfiddle.net/YbZPE/5/

First you have to get teh cell, if you want the first use eq(0): 首先,你必须得到teh cell,如果你想第一次使用eq(0):

$cell = jQuery('#the_table tr td:eq(0)');

then you have to put the class on the parent row: 那么你必须把类放在父行上:

$cell.parent("tr").addClass("hidden");

The following code will do it. 以下代码将执行此操作。

jQuery('#the_table tr td:eq(0)').parent("tr").addClass("hidden");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM