0

有没有可能的方法来创建下一个搜索和使用 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>

这个脚本的问题是它只能找到第一个匹配项......

4

1 回答 1

0

将 RegExp 存储在一个变量中,而不是在每个函数执行时创建一个新的,并且它的计数器属性将lastIndex持续exec()存在。

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>
于 2012-04-17T18:49:52.090 回答