如何将此jQuery code
转换为plain JavaScript
?
$("#txtTestNumbersOnlyRegex").keyup(function () {
var newValue = $(this).val().replace(/[^0-9]/g,'');
$(this).val(newValue);
});
答案 0 :(得分:0)
一种可能的Jquery-> JS转换,
document.getElementById('txtTestNumbersOnlyRegex').addEventListener("keyup", function() {
var newValue = this.value.replace(/[^0-9]/g, '');
this.value = newValue;
});
<input type="text" id="txtTestNumbersOnlyRegex" />
对于angular:像这样抓住你的输入元素
var elm = document.getElementById('txtTestNumbersOnlyRegex')
angular.element(elm );
答案 1 :(得分:0)
使用DOM addEventListener
命令监听元素上的事件:
document.querySelector("#txtTestNumbersOnlyRegex").addEventListener('keyup', function(){
var newValue = this.value.replace(/[^0-9]/g,'');
this.value = newValue;
})
答案 2 :(得分:-1)
简单如下
document.querySelector('#txtTestNumbersOnlyRegex').onkeyup = function() {
var newValue = this.value.replace(/[^0-9]/g, '');
this.value = newValue;
}
更新:使用Angular
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
// app.component.html
<input type="text" [(ngModel)]="value" (keyup)="replacer(value)">
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 4';
text: string;
replacer(value: string) {
this.text = value.replace(/[^0-9]/g, '');
}
}