0

这个小搜索示例有效,但只是第一次。

如何清除 p 元素中的所有类,以便在第二次搜索时,前一次搜索的突出显示不显示?

<!DOCTYPE html>
<html>
    <head>
        <script src="http://www.google.com/jsapi" type="text/javascript"></script>
        <script type="text/javascript">
            google.load('jquery', '1.4.2');
            google.setOnLoadCallback(function() {
                $('#searchButton').click(function() {

                 //remove all added classes so we can search again
                 //jQuery.each($('p'), function() {
                    //$('#' + this).addClass('');
                 //}

                 $('p:contains("' + $('#searchText').val() + '")').addClass('highlight');
                });
            });
        </script>
        <style>
            p.highlight {
                background-color: orange;
            }
        </style>
    </head>
    <body>
        <input id="searchText" value="second" />
        <button id="searchButton">Search</button>
        <p>This is the first entry.</p>
        <p>This is the second entry.</p>
        <p>This is the third entry.</p>
        <p>This is the fourth entry.</p>
    </body>
</html>
4

4 回答 4

2

您可以删除highlight所有的类,p然后对匹配的元素再次进行高亮显示。

$('p').removeClass('hightlight');
于 2010-08-18T16:42:40.457 回答
1

如果要删除所有类,可以在类上使用 removeAttr,或将类设置为“”。所以...

$('#searchButton').bind('click',function(){
  $('p').removeAttr('class');
  // OR
  $('p').attr('class','');
});

没有必要使用“each()”,因为 jQuery 会自动对集合中的所有元素执行这些操作。

于 2010-08-18T16:49:08.757 回答
0

用于removeClass()删除类,然后再次搜索并将类添加到新匹配项中。当我这样做时,我将使用filter()搜索<p>刚刚制作的元素的选择,$('p')而不是进行另一个$(...)调用:

$('#searchButton').click(function() {
    $('p')
        .removeClass('highlight')
        .filter(':contains("' + $('#searchText').val() + '")')
        .addClass('highlight');
});
于 2010-08-18T16:40:48.783 回答
0

使用removeClass

$('p').removeClass('highlight')将仅删除先前搜索中的突出显示类 $('p').removeClass()将从所有 p 中删除所有类

于 2010-08-18T16:41:35.133 回答