猿问

为什么input禁止特殊字符输入我这么做没有效果

function showKeyPress(evt) {

    evt = (evt) ? evt : window.event

    return checkSpecificKey(evt.keyCode);

}


function checkSpecificKey(keyCode) {

    var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~!#¥……&*()——|{}【】‘;:”“'。,、?]‘’";//Specific Key list  

    var realkey = String.fromCharCode(keyCode);

    var flg = false;

    flg = (specialKey.indexOf(realkey) >= 0);

    if (flg) {

        alert('请勿输入特殊字符: ' + realkey);  

        return false;

    }

    return true;

}

document.onkeypress = showKeyPress;

dom结构:


<input class="form-control" type="text" id="activityName" name="activityName" onkeypress="showKeyPress()" >


慕桂英3389331
浏览 559回答 1
1回答

PIPIONE

<script type="text/javascript">var specialKey = "「」[`~!#$^&*()=|{}':;',\\[\\].<>/?~!#¥……&*()——|{}【】‘;:”“'。,、?]‘’". split('');function keyup() {&nbsp; &nbsp; &nbsp;var value = document.getElementById('activityName').value;&nbsp; &nbsp; &nbsp;console.log(value)&nbsp; &nbsp; &nbsp;for (var i = 0; i < specialKey.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (value.indexOf(specialKey[i]) > -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;document.getElementById('activityName').value = value.replace(specialKey[i], '');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}}</script><input class="form-control" type="text" id="activityName" name="activityName" onkeyup="keyup()" >
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答