搜索/返回innerhtml

时间:2018-10-16 19:06:53

标签: javascript string search

如何让Java通过自定义搜索字词搜索/返回innerHTML? 我已经尝试了以下方法,但是它似乎不起作用。我只是不知道在这里使用的方法。

    function search(){
    var source = document.getElementById("info").innerHTML;
    var input = document.getElementById("userInput"); 
    var action = source.search.input;
    if (action > -1){
    document.getElementById("results").innerHTML = "found!";   
    }else{
    document.getElementById("results").innerHTML = "not found!"
    }}

谢谢

1 个答案:

答案 0 :(得分:0)

如果您有字符串,语法为str.search('searchvalue'),它将在找到该值的字符串位置返回起始索引。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search

对您的代码进行一些修改可以解决该问题。

<form>
    <input type="text" id="userInput" />
    <div id="info">
        Maecenas dolor nulla, eleifend nec varius eu, consequat at elit. Proin facilisis enim sit amet ligula consectetur scelerisque. Quisque hendrerit pulvinar odio non auctor. Nulla volutpat porttitor felis, non semper lectus rhoncus vitae. Donec finibus at lectus ac dapibus. Aenean mollis erat vitae neque euismod ornare. Nullam in nunc id tellus porttitor tristique. Pellentesque commodo aliquam auctor.
    </div>
    <button type="button" onclick="search()">Search</button>
    <div id="results">
    </div>
</form>

<script type="text/javascript">
    function search(){
        // assume source is the element that contains the text the user is searching
        var source = document.getElementById("info").innerHTML;
        // input is a textbox or entry element, so we get the value as string
        var input = document.getElementById("userInput").value; 
        // determine the index of the user input, -1 means no match
        var action = source.search(input);
        // populate a results element on the page with the results of the search
        if (action > -1){
            document.getElementById("results").innerHTML = "found!";   
        }else{
            document.getElementById("results").innerHTML = "not found!"
        }
    }
</script>