简体   繁体   English

隐藏除单击之外的所有其他div

[英]Hide the all other div's except one which is clicked

I have list of user and their dates in PHP and onclick of specific user, I want to hide div other than one whose link is clicked For example : 我有用户列表及其在PHP中的日期以及特定用户的onclick,我想隐藏除单击其链接的那个之外的div例如:

 <div class='person' id='add_new_date_8' style='display:none;'>
 <div class='person' id='add_new_date_9' style='display:none;'>
 <div class='person' id='add_new_date_10' style='display:none;'>

<a href='javascript:void(0)' onclick="addMydate('<?PHP echo $id;?>')">Add a new Date?<a/>

So if $id = 8 then hide all div of class person which has id other than ' add_new_date_8 ' 因此,如果$id = 8则隐藏具有除“ add_new_date_8 ”以外的ID的类person所有div

Make it simple in jquery 在jQuery中使其简单

$(document).on('click', '.person', function() {
   $('.person').hide();
   $(this).show();
});

access id in js function. js函数中的访问ID。 and first hide all the div with person class and then show the which have matching id. 然后先将所有div与person类一起隐藏,然后显示具有匹配ID的div。

function addMydate(id){
      $('.person').hide();
      $('#add_new_date_'+id).show();
    }

The other solutions so far will work, however I prefer to use .siblings() 到目前为止,其他解决方案都可以使用,但是我更喜欢使用.siblings()

function addMydate(id){
  var selectedEl = $('#add_new_date'+id);
  selectedEl.siblings().hide(); //siblings() takes all other elements of the same parent
  selectedEl.show();
}

This will prevent the element itself from being hidden and then shown again, and might save you some headaches on animations, should you add those. 这将防止元素本身被隐藏然后再次显示,并且如果您添加了动画,可能会节省一些头痛的动画。

note: this depends on your HTML structure instead of classes, which is a bit less flexible. 注意:这取决于您的HTML结构而不是类,这不太灵活。 You can also use the following to exclude the element you want to show from the elements that get hidden: 您还可以使用以下命令将要显示的元素从隐藏的元素中排除:

$('.person').not('#add_new_date'+id).hide()

You can use siblings to get the siblings of the clicked element. 您可以使用siblings来获取clicked元素的同级。

$(document).on('click', '.person', function() {
    $(this).show().siblings('.person').hide();
});

Get the siblings of each element in the set of matched elements, optionally filtered by a selector. 获取匹配的元素集中每个元素的同级,可以选择使用选择器进行过滤。

Docs: http://api.jquery.com/siblings 文件: http//api.jquery.com/siblings

EDIT 编辑

function addMydate(userId) {
    $('#add_new_date_' + userId).show().siblings('.person').hide();
}

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

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