如何将jQuery code
转换为plain JavaScript
?将jQuery转换为普通JavaScript
$("#txtTestNumbersOnlyRegex").keyup(function() {
var newValue = $(this).val().replace(/[^0-9]/g,'');
$(this).val(newValue);
});
如何将jQuery code
转换为plain JavaScript
?将jQuery转换为普通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;
}
更新:具有角
// 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, '');
}
}
你将如何使用它angular 2 for –
@EladNachum Ill更新Angular的答案 – DININDU
谢谢!但我得到以下错误:错误TypeError:_co.replacer不是一个函数 –
一种可能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);
是否可以解释Down投票? –
使用的聆听您的元素上事件的DOM addEventListener
命令:
document.querySelector("#txtTestNumbersOnlyRegex").addEventListener('keyup', function(){
var newValue = this.value.replace(/[^0-9]/g,'');
this.value = newValue;
})
'$(this).val()'是jQuery – charlietfl
@charlietfl - 忘了那小部分,谢谢! – vsync
עניתילךלמטה,שאלאותימהשתרצה – vsync
谷歌或检查等网站http://youmightnotneedjquery.com/ – taseenb
#2是不是免费的代码转换服务 – charlietfl