Javascript 隐藏子元素时如何删除div元素
我有一份员工名单,组织到他们工作的每个部门。在这个页面的顶部,我有一个搜索框来搜索姓名,还有一个选择框来选择部门。这个很好用。 搜索sayJavascript 隐藏子元素时如何删除div元素,javascript,jquery,Javascript,Jquery,我有一份员工名单,组织到他们工作的每个部门。在这个页面的顶部,我有一个搜索框来搜索姓名,还有一个选择框来选择部门。这个很好用。 搜索say“Person4”时,它将隐藏所有其他人员,但保留其他部门标题。在筛选“Person4”时,是否会隐藏“Department1” $('select')。更改(函数(){ var e2=$(“#dpt”).val().toLowerCase(); var e=新的RegExp(e2); $(departmentfilter).每个(函数(){ if(e.tes
“Person4”
时,它将隐藏所有其他人员,但保留其他部门标题。在筛选“Person4”
时,是否会隐藏“Department1”
$('select')。更改(函数(){
var e2=$(“#dpt”).val().toLowerCase();
var e=新的RegExp(e2);
$(departmentfilter).每个(函数(){
if(e.test(this.innerHTML.toLowerCase())
$(this.show();
其他的
$(this.hide();
});
});
$(“#搜索框”).bind('keyup',function(){
var s2=this.value.toLowerCase();
var s=新的RegExp(s2);
$(personfilter).each(函数(){
if(s.test(this.innerHTML.toLowerCase())
$(this.show();
其他的
$(this.hide();
});
});
全体职员
部门1
部门2
部门1
人1
人2
人3
部门2
人4
人5
人6
首先,您需要使用类而不是重复的id
,因为标识符在同一文档中应该是唯一的:
<div class="departmentfilter"> Department1
<div class="personfilter">Person1</div>
<div class="personfilter">Person2</div>
<div class="personfilter">Person3</div>
</div>
<div class="departmentfilter"> Department2
<div class="personfilter">Person4</div>
<div class="personfilter">Person5</div>
<div class="personfilter">Person6</div>
</div>
$('select')。更改(函数(){
var e2=$(“#dpt”).val().toLowerCase();
var e=新的RegExp(e2);
$('.departmentfilter')。每个(函数(){
if(e.test(this.innerHTML.toLowerCase())
$(this.show();
其他的
$(this.hide();
});
});
$(“#搜索框”).bind('keyup',function(){
var s2=this.value.toLowerCase();
var s=新的RegExp(s2);
$('.departmentfilter').hide();//隐藏所有部门
$('.personfilter')。每个(函数(){
if(s.test($(this).text().toLowerCase()){
$(this.show();
$(this).closest('.departmentfilter').show();//显示相关的
}否则
$(this.hide();
});
});代码>
全体职员
部门1
部门2
部门1
人1
人2
人3
部门2
人4
人5
人6
为什么id
s不是唯一的?还共享“选择和输入”框的标记。@gurvinder372要使搜索功能正常工作,我必须使所有ID都相同。不过我可能做得不对@TCampbell id在文档上下文中必须是唯一的,这样做是错误的。使用类instead@A.Wolff谢谢,但当我将id更改为类时,搜索功能停止工作。有什么想法吗?这就是我想要的,非常感谢!唯一的问题是我还有一个选择框来选择部门以及搜索名称。这不管用了,有什么想法吗?
$('.departmentfilter').hide(); //Hide all departments
$(this).closest('.departmentfilter').show(); //Show the related one