Javascript 如何替换代码以使用RegExp
我有以下代码,用于检查“回车”键,并防止在文本框中使用Javascript 如何替换代码以使用RegExp,javascript,regex,Javascript,Regex,我有以下代码,用于检查“回车”键,并防止在文本框中使用和/gi,“>”); searchText=searchText.replace(/您是说要阻止字符。这里有一个更简单的方法,当键盘按下事件发生时忽略这些字符 如果可以的话,我还建议使用jQuery var ignoredChars=[188190];// $('#myTextField').keydown(函数(e){ if(ignoredChars.indexOf(e.which)>-1){ e、 预防默认值(); e、 停止传播();
和/gi,“>”);
searchText=searchText.replace(/您是说要阻止字符。这里有一个更简单的方法,当键盘按下事件发生时忽略这些字符 如果可以的话,我还建议使用jQuery只需将此事件处理程序添加到文本框中,并删除regexp替换项即可。var ignoredChars=[188190];// $('#myTextField').keydown(函数(e){ if(ignoredChars.indexOf(e.which)>-1){ e、 预防默认值(); e、 停止传播(); 返回false; } }) .keyup(功能(e){ 如果(e.which==13){ $(“#搜索按钮”)。单击(); } });
如果您不想让用户输入字符,请尽早使用它们。这样,您就不会在以后从大字符串中提取字符时遇到麻烦。您正在替换中使用正则表达式。是正则表达式。您想用/
函数做什么?另外,您在正则表达式中使用的是不必要的因为您没有尝试匹配字母。我不能将两者合并为一行吗?我想使用onBlur
因此,当用户离开文本框并替换Lt和gt符号以“确保这不是您唯一的验证。当用户粘贴包含禁止字符的值时会发生什么情况?效果很好。我如何将整个内容替换到JQuery?您是对的,我应该使用JQuery:)更新了答案,以便按enter键将触发搜索按钮。在选择任何DOM元素之前,不要忘记用onBlur()
换行。祝你好运$(document).ready(function(){…})
<script type="text/javascript" language="javascript"> function checkKeycode(e) { var keycode; if (window.event) // IE keycode = e.keyCode; else if (e.which) // Netscape/Firefox/Opera keycode = e.which; if (keycode == 13) { //Get the button the user wants to have clicked var btn = document.getElementById(btnSearch); if (btn != null) { //If we find the button click it btn.click(); event.keyCode = 0 } //Removed when above code was added 12-09-13 //CallSearch(); } } function CallSearch() { var objsearchText = window.document.getElementById('txtSearchText'); var searchText; if ((objsearchText!=null)) { searchText = objsearchText.value; searchText = searchText.replace(/>/gi, " >"); searchText = searchText.replace(/</gi, "< "); objsearchText.value = searchText; } //This cookie is used for the backbutton to work in search on postback //This cookie must be cleared to prevent old search results from displayed document.cookie='postbackcookie='; document.location.href="search_results.aspx?searchtext="; } </script>
var ignoredChars = [188, 190]; // <, > $('#myTextField').keydown(function(e) { if(ignoredChars.indexOf(e.which) > -1) { e.preventDefault(); e.stopPropagation(); return false; } }) .keyup(function(e) { if(e.which === 13) { $('#searchButton').click(); } });