【问题标题】:If query fails with AND but works with OR如果查询使用 AND 失败但使用 OR
【发布时间】:2012-08-20 18:44:56
【问题描述】:

我在 keyup-event 上使用 jQuery 搜索 JSON 树。如果输入等于所需条目,则输入将被禁用。

现在我需要调用一个函数,如果它们都被填满并且正确。 if 查询很长,所以我将它们写入变量。

我试过这个,但它失败

if (simple_present && simple_past && past_participle) {
    alert('All right!');
}

现在,当我写这样的东西时,它有效

if (simple_present || simple_past || past_participle) {
    alert('All right!');
}

这是what I have so far的小提琴。

有什么想法吗?

顺便说一句:将 long if 查询与 reg 表达式结合的最佳方式是什么?

【问题讨论】:

  • 如果你知道如何通过浏览器的开发工具调试 JavaScript...:P(你必须在 if 语句上放置一个断点并检查变量的值在 if-header 中。由于“它失败了”,(至少)其中一个变量显然是虚假的。)
  • @Šime Vidas:我知道你的意思,但要实现这是我对 javascript 的了解很差 ;) 一些代码可能会有所帮助?!

标签: javascript jquery regex json


【解决方案1】:

您在每个元素的同一事件处理程序中运行以下所有代码:

$this.attr('id') == 'simple_present'
$this.attr('id') == 'simple_past'
$this.attr('id') == 'past_participle'

他们不可能都是真的,所以&&保证给你false

【讨论】:

  • 顺便说一句,OP 注意:this.id 工作正常。此处无需使用 jQuery。
  • @yckart:您可能只想验证当前输入字段并拥有跟踪每个文本字段正确性的变量(或对象)。然后,您可以独立验证每个输入。
【解决方案2】:

在 if 之前添加一个调试行:

alert( simple_present.toString() + '\n' + simple_past.toString() + '\n' + past_participle.toString() );

【讨论】:

    【解决方案3】:

    考虑一下:

    var json = {
        "vocables": {
            "irregular": {
                "sein": {
                    "simple_present": "be",
                    "simple_past": "was were",
                    "past_participle": "been"
                },
                "schlagen": {
                    "simple_present": "beat",
                    "simple_past": "beat",
                    "past_participle": "beaten"
                },
                "werden": {
                    "simple_present": "become",
                    "simple_past": "became",
                    "past_participle": "become"
                }
            }
        }
    };
    
    var word = $( 'h1' ).text();
    
    $( 'input' ).on( 'keyup', function () {
        if ( this.value === json.vocables.irregular[ word ][ this.id ] ) {
            $( this ).prop( 'disabled', true ).next( 'input' ).focus();
        }
    
        if ( $( 'input:not(:disabled)' ).length === 0 ) {
            alert( 'SUCCESS' );
        }
    });
    

    现场演示: http://jsfiddle.net/NnAMu/1/

    如你所见,我有:

    • 更改了 JSON 结构以更好地满足我的需求,
    • 将当前单词缓存到一个变量中。

    通过这些更改,生成的“keyup”处理程序代码要简单得多。

    【讨论】:

    • 哇!好多了...非常感谢!
    • @yckart:顺便说一句,你的第三个项目 (werden) 没有简单的过去。
    • @pimvdb:是的,我知道 json 树还没有真正完成;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多