首页 > 解决方案 > 如果相应的元素 hasClass 'active',则 Jquery 添加类(试图简化我的代码)

问题描述

请帮助 - 必须有更好的方法来做到这一点!所以基本上,在一个 svg 中,我有一堆类名为 1 - 50 的元素。然后是一堆 id 为 1 - 50 的对应元素。简而言之 - 如果圈 1 有类热点活动,那么路径 1 应该有类定位器激活等。

我的代码有效,但我真的不想写 50 个 if 语句!我确信这可以用数组来完成,但我的 Jquery 还不够好。任何帮助将不胜感激。这是一个从 1 到 3 的小代码示例 -

$(document).ready(function(){

if ($('.1').hasClass('hotspot-active') ) {
$('#1').addClass('locator-active');
}

});

$(document).ready(function(){

if ($('.2').hasClass('hotspot-active') ) {
$('#2').addClass('locator-active');
}

});

$(document).ready(function(){

if ($('.3').hasClass('hotspot-active') ) {
$('#3').addClass('locator-active');
}

});

HTML 看起来像这样 -

<circle class="1" cx="1078.34" cy="656.84" r="12.75"/>
<circle class="2" cx="1547.13" cy="613.3" r="12.75"/>
<circle class="3 hotspot-active" cx="1578.15" cy="221.17" r="12.75"/>

<path id="1" />
<path id="2" />
<path id="3" />

标签: javascriptjqueryhtmlif-statement

解决方案


您可以用于

$(document).ready(function(){
    const circlesCount = document.querySelectorAll('circle').length;
    for (let i = 1; i <= circlesCount; i++) {
      if ($('.' + i).hasClass('hotspot-active') ) {
        $('#' + i).addClass('locator-active');
      }
    }
});

推荐阅读