2017-10-14 71 views
-4

如何将jQuery code转换为plain JavaScript将jQuery转换为普通JavaScript

$("#txtTestNumbersOnlyRegex").keyup(function() { 
    var newValue = $(this).val().replace(/[^0-9]/g,''); 
    $(this).val(newValue);  
}); 
+0

עניתילךלמטה,שאלאותימהשתרצה – vsync

+0

谷歌或检查等网站http://youmightnotneedjquery.com/ – taseenb

+0

#2是不是免费的代码转换服务 – charlietfl

回答

-1

只需如下

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, ''); 
    } 
} 

Here is the example code

+0

你将如何使用它angular 2 for

+0

@EladNachum Ill更新Angular的答案 – DININDU

+0

谢谢!但我得到以下错误:错误TypeError:_co.replacer不是一个函数 –

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" />

对于角度:抓住你的输入元素这样

var elm = document.getElementById('txtTestNumbersOnlyRegex') 
    angular.element(elm); 
+0

是否可以解释Down投票? –

0

相当容易转换:

使用的聆听您的元素上事件的DOM addEventListener命令:

document.querySelector("#txtTestNumbersOnlyRegex").addEventListener('keyup', function(){ 
    var newValue = this.value.replace(/[^0-9]/g,''); 
    this.value = newValue;  
}) 
+3

'$(this).val()'是jQuery – charlietfl

+0

@charlietfl - 忘了那小部分,谢谢! – vsync