希望在jQuery迭代中只显示/隐藏指定的元素

want to show / hide only the specified elements in jQuery iteration

本文关键字:隐藏 元素 显示 jQuery 迭代 希望      更新时间:2023-09-26

我有以下代码,我想在其中显示/隐藏基于鼠标悬停的不同文本。我正在使用一个数据全局id值,并希望迭代项目列表的子项,并隐藏除指定值之外的所有值(例如,数据全局id=1的项目1):

<script>
  $(document).ready(function() {
    $('.item-list').hide();
    $('.h').mouseover(function() {
      // need to hide everything but the 1 or 2
      var id = $(this).data('global-id');
      var chil=$('.item-list').children();
      $.each(chil, function(i,v){
        alert(i);
        console.log(v);
      });
    });
  });
</script>
<style>
.h{
  width: 200px;
  border: 1px solid red;
}
</style>
<ul>
    <li><div class='h' data-global-id="1">Client 1</div></li>
    <li><div class='h' data-global-id="2">Client 2</div></li>
</ul>
<ul class="item-list">
    <li class="item-1">
        Lorem ipsum jtjtjt, etc...
    </li>
    <li class="item-2">
        Lorem ipsum, etc...
    </li>                      
</ul>

如何在每个循环中指定隐藏所有内容并只显示项+数据全局id值?有更好/更容易的方法吗?

thx

我不完全确定这是否是你想要的,但我无论如何都会试一试,

由于您已经在项目中使用jQuery,因此可以根据data-global-id值进行直接搜索,如下所示

//Provide the same global-id key to each .item-list member
//Then do the following in your mouse over func
 var id = $(this).data('global-id');
 var chil=$('.item-list').children().show().
             not('[data-global-id="'+ id +'"]').hide();

编辑-添加了Fiddle

在这里查看小提琴