代码之家  ›  专栏  ›  技术社区  ›  NightPorter

如果对应的元素有class'active'(试图简化我的代码),Jquery add class

  •  1
  • NightPorter  · 技术社区  · 7 年前

    请帮忙-一定有更好的办法!所以基本上,在svg中,我有一堆类名为1-50的元素,然后是一堆id为1-50的对应元素。

    $(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" />
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Alon Shmiel    7 年前

    你可以用 for

    $(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');
          }
        }
    });
    
        2
  •  0
  •   Andreas    7 年前

    您可以从“活动”圆圈中获取号码/id,然后找到并“激活”相应的路径:

    const hotspot = document.querySelector(".hotspot-active");
    const id = Array.from(hotspot.classList).find(Number);
    
    if (id) {               
      document.getElementById(id).classList.add("locator-active");
    }
    

    但是。。。只有在 .classList

    例子:

    $(function() {
      randomHotspot();
    
      const hotspot = document.querySelector(".hotspot-active");
      const id = Array.from(hotspot.classList).find(Number);
      
      if (id) {               
        document.getElementById(id).classList.add("locator-active");
      }
    });
    
    function randomHotspot() {
      const possibleHotspots = document.querySelectorAll("div"),
            idx = ~~(Math.random() * 3);
      
      possibleHotspots[idx].classList.add("hotspot-active");
    }
    div.hotspot-active { border: solid 2px red }
    p.locator-active { border: solid 2px green }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="1">1</div>
    <div class="2">2</div>
    <div class="3">3</div>
    
    <p id="1">Path 1</p>
    <p id="2">Path 2</p>
    <p id="3">Path 3</p>