多个ID和一张图片

时间:2018-09-10 19:52:17

标签: jquery

jQuery是否有一种干净的方法来执行条件语句,该条件语句会删除基于ID的显示图像。我尝试了一项声明,并不断获得需要的结果和该图像的结果。

//Text Hover to view image in Departments/Shopping
$(document).ready(function() {
  if ($('html').attr('id') == 'appleStoreMenuLabel') {
    $(this.id).hover(
      function() {
        $("#appleStoreLogo").show();
      },
      function() {
        $("#appleStoreLogo").hide();
      }
    );
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="dropdown-submenu" role="menu">
  <a tabindex="1" href="searchResults.html" id="appleStoreMenuLabel">
            Apple Store</a>
  <ul class="dropdown-menu">
    <li><a href="searchResults.html" id="appleStoreMenuLabel1">iPods
                </a></li>
    <li><a href="searchResults.html" id="appleStoreMenuLabel2">iPod
                    Accessories </a></li>
    <li><a href="searchResults.html" id="appleStoreMenuLabel3">Watches</a></li>
    <li><a href="searchResults.html" id="appleStoreMenuLabel4">Mac
                    Systems</a></li>
    <li><a href="searchResults.html" id="appleStoreMenuLabel5">iPads</a></li>
    <li><a href="searchResults.html" id="appleStoreMenuLabel6">Shop
                    All Apple Store</a></li>
  </ul>
</li>

1 个答案:

答案 0 :(得分:0)

使用类而不是ID。

将HTML id=appleStoreMenuLabel1id=appleStoreMenuLabel2 ...更改为使用class=appleStoreMenuLabel

然后将您的JS更改为以下内容:

$('.appleStoreMenuLabel').hover(function () {
        $("#appleStoreLogo").show();
    },
    function() {
        $("#appleStoreLogo").hide();
});

更新

<ul class="dropdown-menu">
    <li><a href="searchResults.html" id="iPods" class="appleStoreMenuLabel">iPods</a></li>
    <li><a href="searchResults.html" id="iPodAccessories" class="appleStoreMenuLabel">iPod Accessories </a></li>
    <li><a href="searchResults.html" id="watches" class="appleStoreMenuLabel">Watches</a></li>
    ...
</ul>

<!-- somewhere on your page -->
<img id="iPodAccessoriesimage" />
<img id="iPodsimage" />
<img id="watchesimage" />

$('.appleStoreMenuLabel').hover(function (event) {
            $("#" + event.target.id + "image").show();
        },
        function() {
            ("#" + event.target.id + "image").hide();
    });