有没有办法在条件为真时执行jQuery链接的分支

Cod*_*key 6 javascript jquery conditional-statements

我可能大约有7或8个熟悉jQuery(1-10级),所以我不确定这是否有意义,但我想知道是否有人知道jQuery函数或可能是一个插件,它允许只有在给定条件为真时才执行jQuery分支.否则,我很想听听有人认为这个概念在某种程度上是有缺陷的(编辑以及它是如何有缺陷的)

虽然可以使用类似于此的常规JavaScript语法控制各种事件的附件:

var desiredElement = $('.parent')                        // find the parent element
                     .hover(overFunction,offFunction)    // attach an event while I've got the parent in 'scope'
                     .find('.child-element');            // then find and return the child
if (booleanVar1) {                                       // if one condition
    desiredElement.click(clickFunction1);                //   attach one event
} else if (booleanVar2) {                                // or if a different condition
    desiredElement.click(clickFunction2);                //   attach a different event
} else {                                                 // otherwise
    desiredElement.click(clickFunction3);                //   attach a default event
}
$('.parent').find('.other-child')                        // (or $('.parent .other-child')
    .css(SomePredefinedCssMapping)
    .hide()
//...
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法在jQuery中完成所有操作,或者是否有充分的理由不...可能是这样的:

$('.parent')                                // find the parent element
    .hover({overFunction,offFunction})      // attach an event while I've got the parent in 'scope'
    .find('.child-element')                 // then find the child
        .when(booleanVar1)                  // if one condition
            .click(clickFunction1)          //   attach one event
        .orWhen(booleanVar2)                // or if a different condition
            .click(clickFunction2)          //   attach a different event
        .orElse()                           // otherwise
            .click(clickFunction3)          //   attach a default event
        .end()
    .end()
    .find('.other-child')
        .css(SomePredefinedCssMapping)
//...
Run Code Online (Sandbox Code Playgroud)

注意:我认为这在语法上是正确的,假设布尔值和函数被正确定义,但我很确定我的意图非常明确

建议的jQuery似乎对我来说有点整洁(??)同意/不同意? - 所以这是我的问题:

  • 是否有一些本机jQuery基本上已经这样做了?
  • 是否有扩展已经允许这种类型的东西?
  • 比我想的更难吗?(我认为如果条件为真,保持当前元素集,如果条件为假则推送空元素集,然后为每个or条件弹出元素集,就会这样做,就像end()方法弹回前一个find()通话后设定)
  • 是否存在使其效率显着降低的问题?

编辑

该问题询问如何使用方法链接或为什么它不可取(特定首选).虽然它没有要求替代方案,但可能需要这样的替代方案来解释jQuery链接方法的问题.此外,由于上面的示例立即评估布尔值,因此任何其他解决方案都应该这样做.

Esa*_*ija 2

$('.parent').hover(overFunction,offFunction)
    .find('.child-element')
    .click( booleanVar ? clickFunction1 :
            booleanVar2 ? clickFunction2 :
            clickFunction3 )
    .end()
    .find('.other-child')
    .css(SomePredefinedCssMapping)
Run Code Online (Sandbox Code Playgroud)