【问题标题】:How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'如何在 JavaScript -JQuery 中否定“if”语句块中的代码,例如“if not then ..”
【发布时间】:2011-10-04 18:31:08
【问题描述】:

例如,如果 used 元素的父元素没有 ul 标记作为下一个元素,我想做什么,我该如何实现?

我尝试了.not() 和/或的一些组合 .is() 没有成功。

if else 块的代码求反的最佳方法是什么?

我的代码

if ($(this).parent().next().is('ul')){
   // code...
}

我想实现这个

伪代码:

if ($(this).parent().next().is NOT ('ul')) {
    //Do this..
}

【问题讨论】:

  • 你可以把jQuery从这个问题中去掉。
  • 当你说下一个时,你真的是指下一个,就像父母的兄弟姐妹一样,还是你的意思是别的?
  • @Tomalak - 标签的唯一理由是包含它有助于为他的问题设置上下文......
  • @Justin:你也可以标记它ulDOM

标签: javascript jquery if-statement conditional-statements


【解决方案1】:

您可以使用逻辑非 ! 运算符:

if (!$(this).parent().next().is('ul')){

或等效(见下面的 cmets):

if (! ($(this).parent().next().is('ul'))){

有关详细信息,请参阅 MDN 文档的 Logical Operators 部分。

【讨论】:

    【解决方案2】:

    $(this)之前尝试否定运算符!

    if (!$(this).parent().next().is('ul')){
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2022-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      相关资源
      最近更新 更多