2012-04-17 84 views
0

是否有任何可能的方式來創建一個搜索和搜索所有按鈕與JavaScript?這是我的腳本到目前爲止...搜索下一個按鈕javascript

<script type="text/javascript"> 
    function setSelectionRange(input, selectionStart, selectionEnd) 
    { 
     input.focus(); 
     input.setSelectionRange(selectionStart, selectionEnd); 
    } 
    function selectString (input, string) 
    { 
     var match = new RegExp(string, "g").exec(input.value); 
     if (match) 
    { 
    setSelectionRange (input, match.index, match.index + match[0].length); 
    } 
    } 
</script> 

<form action="" method="get" onsubmit="selectString(document.getElementById('text'), document.getElementById('search').value);return false;">    
     <legend> 
      <font face="verdana">Zoekveld</font face> 
     </legend> 
     <input id="search" name="search" type="text" size="75"> 
     <input type="submit" value="Zoeken"> 
</form> 

<form name=form1 method="get"> 
     <legend> 
      <font face="Verdana">Vind:</font face> 
     </legend> 
     <textarea id="text" cols="54" rows="20"></textarea> 
</form> 

與該腳本的問題是,它只能找到的第一個匹配.. 。

回答

0

Store中的正則表達式我ñ一個變量,而不是創建一個新的每個功能執行,它的計數器屬性lastIndexexec()將持續。

var r = /^$/; 
function setSelector(string) { 
    r = new RegExp(string, "i"); 
} 
function selectNextMatch(input) { 
    var match = r.exec(input.value); 
    if (match) 
     setSelectionRange(...); 
    else 
     alert("Nothing found"); 
} 
<input type="text" size="75" onchange="setSelector(this.value);"> 
<input type="button" value="Zoeken" onclick="selectNextMatch(document.getElementById('text'));"> 
<textarea id="text" cols="54" rows="20"></textarea> 
+0

所以,如果我只是把它變成: VAR的匹配=新的RegExp(字符串, 「I」)lastIndex的(input.value); 它應該工作? 但它並不:(爲是在JavaScript這樣的小白對不起......(那你能不能改變我的劇本我......或者告訴我怎麼做,或在那裏我能得到的教程或東西?) – user1339469 2012-04-22 13:15:55

+0

我添加了一個例子。我不知道*當你*正在努力尋找其他的比賽中,腳本取決於這一點。 – Bergi 2012-04-23 19:47:40

+0

奧凱我會試着改變我的代碼。我試圖找到所有匹配Thx幫助到目前爲止:) – user1339469 2012-04-24 06:43:00