如何使用 JavaScript 将我的电话号码格式化为 xxxx-xxx-xxx?

我需要像xxxx-xxx-xxx使用 JavaScript 一样格式化我的电话号码,我该如何制作呢?


下面是代码:


超文本标记语言


<input onkeypress="isInputNumber(event)" type="text"  id="phonenumber" placeholder = "xxxx-xxx-xxxx" maxlength="11"/>

JavaScript


function isInputNumber(evt){

    var ch=String.fromCharCode(evt.which);

    if(!(/[0-9]/.test(ch))){

          evt.preventDefault();

    }

}


扬帆大鱼
浏览 111回答 1
1回答

哆啦的时光机

document.getElementById('phonenumber').addEventListener('blur', function (e) {&nbsp; &nbsp; &nbsp; &nbsp; var x = e.target.value.replace(/\D/g, '').match(/(\d{4})(\d{3})(\d{4})/);&nbsp; &nbsp; &nbsp; &nbsp; e.target.value =&nbsp; x[1] + '-' + x[2] + '-' + x[3];&nbsp; &nbsp; });&nbsp; &nbsp;&nbsp;function isInputNumber(evt){&nbsp; &nbsp; &nbsp; &nbsp; var ch=String.fromCharCode(evt.which);&nbsp; &nbsp; &nbsp; &nbsp; if(!(/[0-9]/.test(ch))){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; evt.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input onkeypress="isInputNumber(event)" type="text"&nbsp; id="phonenumber" placeholder = "xxxx-xxx-xxxx" maxlength="11"/>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5