【问题标题】:If (.somthing:contains(text).addClass, if else (:contains(otherText).addClassif (.something:contains(text).add Class, if else (:contains(other Text).addClass
【发布时间】:2013-06-06 14:31:47
【问题描述】:

简短的故事:我们失去了我们的 php 人,直到我们得到一个新的人,我正在使用这种 hackey 方法来实现将图标添加到 tr 的目标。

所以我得到了这张表,其中包含 4 个要应用图标的类别,我正在尝试编写 if else 语句,但没有得到我想要的结果。这是我的代码的脏版本:

if ($('.summary:contains("Sharks")').each(function () {
     $(this).parent().children('.category').addClass('shark-icon');
});
elseif ($('.summary:contains("Whale")').each(function () {
     $(this).parent().children('.category').addClass('whale-icon');
});

当退出 if 语句时,工作正常,但我似乎无法让 if else 继续下去。有什么想法吗?

【问题讨论】:

  • 您不需要if elsejQuery 已经只选择了那些。

标签: jquery if-statement contains


【解决方案1】:
$('.summary:contains("Sharks")').siblings('.category').addClass('shark-icon');
$('.summary:contains("Whale")').siblings('.category').addClass('whale-icon');

应该这样做。

您首先不需要if else 子句,因为选择器将过滤项目,您可以直接将类添加到tr

如果 category 是 td 上要应用该类的类,请使用 .siblings 方法

【讨论】:

  • 感谢您抽出宝贵时间查看!
【解决方案2】:

试试这个方法-

$('.summary').each(function () {
    if($(this).is(':contains("Sharks")')){ 
        $(this).parent().children('.category').addClass('shark-icon');
    } else if($(this).is(':contains("Whale")')){ 
        $(this).parent().children('.category').addClass('whale-icon');
    }
});

【讨论】:

  • 感谢您的帮助,非常感谢。这很好用,但必须使用更短的代码。
猜你喜欢
  • 2022-12-14
  • 2019-04-05
  • 2011-04-26
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
相关资源
最近更新 更多