如何从 $('p') 集合中删除所有类?
这个小搜索示例有效,但只是第一次。
如何清除 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>
This little search example works but only the first time.
How do I clear all the classes from the p elements so when searching the second time, the highlight from the previous search doesn't show?
<!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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以删除所有
p
上的highlight
类,然后在匹配的元素上再次突出显示。You can remove the
highlight
class on all thep
then do hightlight again on matched elements.如果要删除所有类,可以在类上使用removeAttr,或将类设置为“”。所以...
使用“each()”是不必要的,因为 jQuery 会自动对集合中的所有元素执行这些操作。
If you want to remove ALL classes, you can use removeAttr on class, or set class to "". So...
Using "each()" isn't necessary because jQuery will automatically perform these actions on all elements within the collection.
使用 removeClass
$('p').removeClass('highlight')
将仅从之前的搜索中删除突出显示的类别$('p').removeClass()
将从所有 p 中删除所有类Use removeClass
$('p').removeClass('highlight')
will remove just the highlight class from the previous search$('p').removeClass()
will remove all classes from all p's使用
removeClass()
删除该类,然后再次搜索并将该类添加到新的匹配项中。当我这样做时,我将使用filter()
来搜索刚刚使用$('p 创建的
而不是进行另一个元素的选择')
$(...)
调用:Use
removeClass()
to remove the class, then search again and add the class to the new matches. While I'm at it, I'll usefilter()
to search the selection of<p>
elements that was just made with$('p')
instead of doing another$(...)
call: