2014-01-20 17 views
0

我有下面的代碼檢查「ENTER」鍵,以及防止在文本框中使用><標誌。如何更換代碼中使用正則表達式

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

我怎樣才能縮短代碼更effecient並使用onBlur功能和使用RegExp,而不是取代?或者取代比RegExp更快的方法?

+2

您在替換中使用正則表達式。 '/> /'是一個正則表達式。 –

+0

你想使用'onBlur'函數來做什麼?另外,您在正則表達式中使用的[i修飾符](http://www.w3schools.com/jsref/jsref_regexp_i.asp)是不必要的,因爲您並不試圖匹配字母。 – NathanW

+0

我不能將兩者合併爲一行嗎?我想使用'onBlur()',這樣當用戶離開文本框並將Lt和gt替換爲'' – Si8

回答

1

你是說你要防止<>字符。這是一種更簡單的方法,只要在它們上面發生keydown事件時忽略這些字符。

另外我建議使用jQuery - 如果可以的話。

http://api.jquery.com/event.which/

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(); 
    } 
}); 

此事件處理程序只需添加到您的文本框和除去正則表達式替代品。 如果你不想讓用戶輸入字符,儘可能早地抑制它們。這樣你以後就不會麻煩地擺弄他們。

+0

工程很棒。如何將整個事件替換爲JQuery?你是對的,我應該去與JQuery :) – Si8

+1

更新的答案,以便按下回車鍵將觸發搜索按鈕。在選擇任何DOM元素之前,不要忘記用'$(document).ready(function(){...})來包裝。祝你好運 – angabriel

相關問題