简体   繁体   English

JQuery突出显示无法正常工作

[英]JQuery highlight not working properly

Reference 参考

I am trying to build a form with the functionality something similar to word search. 我正在尝试构建一个具有与单词搜索类似的功能的表单。

I have a text-area and a series of divs with contents. 我有一个文本区域和一系列内容的div。 When a user types a word or a sentence, the words that match with the div contents are highlighted in yellow and when text-area content is removed or emptied, highlighting is also removed. 当用户键入单词或句子时,与div内容匹配的单词以黄色突出显示,并且当删除或清空文本区域内容时,也会删除突出显示。

The sample that I made highlights the words but doesn't highlight it completely. 我制作的样本突出了单词,但没有完全突出显示。 Only first character is highlighted. 仅突出显示第一个字符。 And when I try to search for a new word, previously highlighted words are still highlighted. 当我尝试搜索新单词时,之前突出显示的单词仍会突出显示。

HTML HTML

<textarea id="my_ta" name="my_ta"></textarea>
<hr>
    Similiar Words
<hr>
<div>
    This is a serious question   
</div>
<div>
    Does this question ring a bell inside your head?
</div>    
<div>
    This question is a question about questions    
</div>   

CSS CSS

.highlight { background-color: yellow }

JavaScript JavaScript的

$(document).ready(function(){
    $('#my_ta').keypress(function()
    {                                           
        var value = $(this).val();
        if(value)
        {
            $('div').highlight(value); 
        }
        else
        {
          $('.highlight').removeHighlight();
        }
    });        
 });

FIDDLE 小提琴

Looking at the documentation, seems that you'de be good to go just with 看一下这些文档,看起来你会很高兴

$(document).ready(function(){
    $('#my_ta').on('input',function(){
        $('div').removeHighlight().highlight($(this).val()); 
    });        
});

Use input or keyup instead of keypress . 使用inputkeyup而不是keypress http://jsfiddle.net/2vsgbmgz/3/ http://jsfiddle.net/2vsgbmgz/3/

Rather use Regular Expressions. 而是使用正则表达式。 It's easier to find anything you're looking for. 找到你想要的任何东西都比较容易。


HTML HTML

<div>
You can have any text inside a <div>
or any valid html tag you want. 
</div>

CSS CSS

#highlight {
    background-color: red
}

jQuery jQuery的

function highlight() {
    $.each($('div'), function() {
        //-------------------------Get Text
        var str = $(this).html();
        //-------------------------Wrap Matching Text
        str = str.replace(/hi/ig, '<span id="highlight">$&</span>');
        //-------------------------Insert Coloured Text
        $(this).html(str);
    });
}
highlight();

jsFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM