InArray不会识别这个值,但会识别正常数字

时间:2017-07-11 15:49:00

标签: javascript jquery



import { MyDialog } from './my-dialog/my-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { DomSanitizer } from '@angular/platform-browser';
import { SecurityContext } from '@angular/core';

// ...
export class AppComponent {
  htmlContent: string = '<p>Content goes here</p>';
  constructor(private dialog: MatDialog, private dom: DomSanitizer){}

  openDialog() {
    let dialogRef = this.dialog.open(MyDialog);
    dialogRef.componentInstance.htmlContent = this.dom.sanitize(SecurityContext.HTML, this.htmlContent);
  }
}
&#13;
$('#something').on("keydown", function(e) {
        var x = [0,6,7,3,2];
        var y = this.value;
        var z = $.inArray(y, x);
        if(z > -1){
            alert('EXISTS');
        }
    });
&#13;
&#13;
&#13;

我的代码在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='number' id='something'>处不起作用,但如果我将其替换为y = this.value,则按预期工作,为什么不能使用y = 0; < / p>

1 个答案:

答案 0 :(得分:1)

问题是因为你的数组充满了整数,但this.value是一个字符串。您需要将类型转换为匹配。

另请注意,使用keyupinputkeydown更有意义,否则之前的值只会在下一个事件发生时进行评估。试试这个:

&#13;
&#13;
$('#something').on("input", function(e) {
  var x = [0, 6, 7, 3, 2];
  var y = parseInt(this.value, 10);
  var z = $.inArray(y, x);
  if (z > -1) {
    console.log('EXISTS');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='something'>
&#13;
&#13;
&#13;