[英]Convert jQuery to plain JavaScript
如何将此jQuery code
转换为plain JavaScript
?
$("#txtTestNumbersOnlyRegex").keyup(function () {
var newValue = $(this).val().replace(/[^0-9]/g,'');
$(this).val(newValue);
});
简单如下
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, '');
}
}
一种可能的 Jquery->JS 转换,
document.getElementById('txtTestNumbersOnlyRegex').addEventListener("keyup", function() { var newValue = this.value.replace(/[^0-9]/g, ''); this.value = newValue; });
<input type="text" id="txtTestNumbersOnlyRegex" />
对于角度:像这样抓住你的输入元素
var elm = document.getElementById('txtTestNumbersOnlyRegex')
angular.element(elm );
使用 DOM addEventListener
命令侦听元素上的事件:
document.querySelector("#txtTestNumbersOnlyRegex").addEventListener('keyup', function(){
var newValue = this.value.replace(/[^0-9]/g,'');
this.value = newValue;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.