繁体   English   中英

将 jQuery 转换为纯 JavaScript

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM