制作更智能的 jQuery 代码应用于 WordPress 菜单

问题描述 投票:0回答:1
jquery wordpress menu
1个回答
0
投票

您需要委托 - 如果您使用数据属性,生活会变得更轻松

$(function() {
  $('li[id^="menu-item"]').on("mouseenter mouseleave", function(event) {
    $(`p.${this.dataset.target}`).toggleClass("hover", event.type === "mouseenter");
  });
});
p.hover {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<ul>
  <li id="menu-item-227" data-target="custom-class-1" class="menu-item">227</li>
  <li id="menu-item-228" data-target="custom-class-2" class="menu-item">228</li>
  <li id="menu-item-n" data-target="custom-class-n " class="menu-item">n</li>
</ul>
<div>
  <p class="custom-class-1">P 1 </p>
  <p class="custom-class-2">P 2</p>
  <p class="custom-class-n">P n</p>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.