-3

IF 条件ロジックは正しいですか? test1 では機能しますが、test2 または "" では機能しません

      if($(this).attr("value") === ("test1" || "test2" || ""))
      {
          submitForm($(this).attr("value"));
      }
4

3 に答える 3

3

可能な各値を再度テストする必要があります。

if($(this).attr("value") === "test1" || $(this).attr("value") === "test2" || $(this).attr("value") === ""))

一時変数でクリーンアップ:

var attribute = $(this).attr("value");
if(attribute === "test1" || attribute === "test2" || attribute === ""))

indexOf()代わりに、省略形として使用できます:

if (["test1", "test2", ""].indexOf($(this).attr("value")) != -1)
于 2013-09-10T22:27:04.977 に答える
1
if($(this).attr("value") === ("test1" || "test2" || "")) {
    submitForm($(this).attr("value"));
}

ここで何が起こっているのですか?OR ||演算子は最初の真の値を返すための戻り値は("test1" || "test2" || "")です"test1"。この場合、この式は次のように解釈されます。

(("test1" || "test2") || "")

評価される最初の式は"test1" || "test2"であり、これ"test1"は真の値であるため返されます。2つ目の表現は"test1" || "". 再び戻ります"test1"(しかもfalsy です"") 。

これに似たものを書く非常に速い方法は、配列内を検索することです:

var acceptedValues = ["test1", "test2", ""];
if(acceptedValues.indexOf(this.value) != -1) submitForm(this.value);

この単純な操作では、jQuery は必要ありません!

于 2013-09-10T22:30:37.900 に答える
0
if($.inArray(this.value,['test1','test2','test3']) != -1){
    //...
}
于 2013-09-10T22:28:49.783 に答える