您需要委托 - 如果您使用数据属性,生活会变得更轻松
$(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>