6

我对 jQuery 的熟练程度可能大约为 7 或 8(等级为 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()
//...

我想知道是否有一种方法可以在 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)
//...

注意:我认为这在语法上是正确的,假设布尔值和函数定义得当,但我很确定我已经很清楚地理解了意图

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

  • 本机 jQuery 的某些部分基本上已经这样做了吗?
  • 是否已经有一个扩展允许这种类型的事情?
  • 做起来比我想象的难吗?(我想如果条件为真则保持当前元素集,如果条件为假则推入一个空元素集,然后为每个or条件弹出元素集就可以了,就像end()方法弹出前一个通话后设置find()
  • 有什么东西会显着降低效率吗?

编辑

该问题询问如何使用方法链接来执行此操作,或者为什么不建议这样做(首选具体情况)。虽然它不要求替代方案,但可能需要这样的替代方案来解释 jQuery 链接方法的问题。此外,由于上面的示例立即评估布尔值,因此任何其他解决方案都应该这样做。

4

2 回答 2

2
$('.parent').hover(overFunction,offFunction)
    .find('.child-element')
    .click( booleanVar ? clickFunction1 :
            booleanVar2 ? clickFunction2 :
            clickFunction3 )
    .end()
    .find('.other-child')
    .css(SomePredefinedCssMapping)
于 2012-04-26T19:23:06.933 回答
2

你不能在你的处理程序中执行那个条件逻辑吗?

var boolVar1 = true,
    boolVar2 = false;

$(".foo").on("click", function(){
  if ( boolVar1 ) clickFunction1();
  if ( boolVar2 ) clickFunction2();
});
于 2012-04-26T19:18:28.107 回答