了解Javascript三元语句代码片段

Understanding Javascript ternary statement code snippet

本文关键字:三元 语句 代码 片段 Javascript 了解      更新时间:2023-09-26

我看到了下面的代码片段,并试图理解它。我知道我们正在使用三元运算符,并在menuclick上添加活动类,但请详细解释。

navClick: function (o) { 
var _this = this //what does this refer to
//what does this line of code do especially the equal sign
!_this.menuclicked ?(($(".last-menuitem").attr("id")==$("#menu li.active").find("a:last-child").not(".ignore-ele").attr("class") 
|| $(".last-menuitem").find(".view-holder").attr("id")==$("#menu li.active").find("a:last-child").not(".ignore-ele").attr("class") 
|| ($(window).scrollTop() + $(window).height() >= $(document).height() - 20))?($(".last-menuitem").length!=0 && $(".arrow").addClass('yellow'))
:($(".arrow").removeClass('yellow'))):
}

感谢

!_this.menuClicked

我假设menuClicked是菜单是否被点击的布尔表示。因此,这意味着如果菜单被点击,则返回false。因为!是一个否定算子

因此,如果!_this.menuClicked == true,则执行

(($(".last-menuitem").attr("id") == $("#menu li.active").find("a:last-child").not(".ignore-ele").attr("class") 
|| 
$(".last-menuitem").find(".view-holder").attr("id") == $("#menu li.active").find("a:last-child").not(".ignore-ele").attr("class") 
|| 
($(window).scrollTop() + $(window).height() >= $(document).height() - 20))

(".last-menuitem").attr("id") == $("#menu li.active").find("a:last-child").not(".ignore-ele").attr("class") 

第一个或检查lastMenuItems id是否等于活动菜单项最后一个子项,该子项上没有ignore else类。

如果这是真的,我们去嵌套的转弯

($(".last-menuitem").length!=0 && $(".arrow").addClass('yellow'))

它检查最后一个菜单项类中是否有元素,然后使带有.arrow类的元素具有黄色css样式。

如果嵌套turnery的第一部分是false,那么我们进入第二部分

$(".last-menuitem").find(".view-holder").attr("id") == $("#menu li.active").find("a:last-child").not(".ignore-ele").attr("class") 

也就是说,如果具有视图持有者类id的lastmenuItem等于上一次调用的活动菜单项,而该活动菜单项上没有忽略else类。

做前面提到的真实部分。如果不进行嵌套turnery 的第三部分

($(window).scrollTop() + $(window).height() >= $(document).height() - 20))如果滚动位置+窗口高度大于文档高度-20,则返回true。并完成嵌套turnery的真实部分。否则,如果所有返回错误,则执行错误部分

($(".arrow").removeClass('yellow'))):

如果所有内容都为false,请使用.arrow类从元素中移除黄色。下面是被分解为可读的turnery

!_this.menuclicked ?
(
     (
      $(".last-menuitem").attr("id") == $("#menu li.active").find("a:last-     
      child").not(".ignore-ele").attr("class") 
      ||    $(".last-menuitem").find(".view-holder").attr("id") == $("#menu 
             li.active").find("a:last-child").not(".ignore-ele").attr("class") 
       ||    ($(window).scrollTop() + $(window).height() >= $(document).height() 
             - 20)
      )
?  ($(".last-menuitem").length!=0 && $(".arrow").addClass('yellow'))
: ($(".arrow").removeClass('yellow'))
):