Javascript 如何从$(';p';)集合中删除所有类?
这个小小的搜索示例可以工作,但只是第一次 如何清除p元素中的所有类,以便在第二次搜索时,不会显示上一次搜索中的突出显示?Javascript 如何从$(';p';)集合中删除所有类?,javascript,jquery,addclass,Javascript,Jquery,Addclass,这个小小的搜索示例可以工作,但只是第一次 如何清除p元素中的所有类,以便在第二次搜索时,不会显示上一次搜索中的突出显示? <!DOCTYPE html> <html> <head> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"&
<!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>
load('jquery','1.4.2');
setOnLoadCallback(函数(){
$(“#搜索按钮”)。单击(函数(){
//删除所有添加的类,以便我们可以再次搜索
//每个($('p'),函数(){
//$(“#”+this.addClass(“”);
//}
$('p:contains('+$('#searchText').val()+')).addClass('highlight');
});
});
p、 突出显示{
背景颜色:橙色;
}
搜寻
这是第一个条目
这是第二个条目
这是第三个条目
这是第四个条目
使用removeClass()
删除该类,然后再次搜索并将该类添加到新的匹配项中。在搜索过程中,我将使用filter()
搜索刚刚使用$('p')
创建的
元素的选择,而不是执行另一个$(…)
调用:
$('#searchButton').click(function() {
$('p')
.removeClass('highlight')
.filter(':contains("' + $('#searchText').val() + '")')
.addClass('highlight');
});
使用removeClass()
删除该类,然后再次搜索并将该类添加到新的匹配项中。在此过程中,我将使用filter()
搜索仅使用$('p')
创建的
元素的选择,而不是执行另一个$(…)
调用:
$('#searchButton').click(function() {
$('p')
.removeClass('highlight')
.filter(':contains("' + $('#searchText').val() + '")')
.addClass('highlight');
});
使用
$('p')。removeClass('highlight')
将仅从上一次搜索中删除highlight类
$('p')。removeClass()
将从所有p的使用中删除所有类
$('p')。removeClass('highlight')
将仅从上一次搜索中删除highlight类
$('p')。removeClass()
将从所有p中删除所有类您可以删除所有p
上突出显示的类,然后在匹配的元素上再次高亮显示
$('p').removeClass('hightlight');
您可以删除所有p
上的高亮显示
类,然后在匹配的元素上再次高亮显示
$('p').removeClass('hightlight');
若要删除所有类,可以在类上使用removeAttr,或将类设置为“”。所以
没有必要使用“each()”,因为jQuery将自动对集合中的所有元素执行这些操作。如果要删除所有类,可以在类上使用removeAttr,或将类设置为“”。因此
没有必要使用“each()”,因为jQuery将自动对集合中的所有元素执行这些操作