Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果对应的元素有class';主动';(试图简化我的代码)_Javascript_Jquery_Html_If Statement - Fatal编程技术网

Javascript 如果对应的元素有class';主动';(试图简化我的代码)

Javascript 如果对应的元素有class';主动';(试图简化我的代码),javascript,jquery,html,if-statement,Javascript,Jquery,Html,If Statement,请帮忙,一定有更好的办法!所以基本上,在svg中,我有一堆类名为1-50的元素。然后是一组id为1-50的对应元素。 简而言之,如果圆1的类热点处于活动状态,那么路径1的类定位器应该处于活动状态,依此类推 我的代码可以工作,但我真的不想写50条if语句!我确信这可以通过数组实现,但我的Jquery还不够好。任何帮助都将不胜感激。 下面是一个从1到3的小代码示例- $(document).ready(function(){ if ($('.1').hasClass('hotspot-active

请帮忙,一定有更好的办法!所以基本上,在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" />

您可以使用

$(文档).ready(函数(){
const circlescont=document.querySelectorAll('circle')。长度;

对于(设i=1;i您可以从“活动”圆圈中获取编号/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
中找到的第一个数字是相应路径元素的id时,这项功能才能正常工作

例如:

$(函数(){
随机热点();
const hotspot=document.querySelector(“.hotspot活动”);
const id=Array.from(hotspot.classList).find(Number);
如果(id){
document.getElementById(id).classList.add(“定位器激活”);
}
});
函数{
const possibleHotspots=document.queryselectoral(“div”),
idx=~~(Math.random()*3);
可能热点[idx].classList.add(“热点活动”);
}
div.hotspot-active{边框:实心2px红色}
p、 定位器活动{边框:实心2px绿色}

1.
2.
3.
路径1

路径2


路径3

这真是太棒了。感谢你花时间写这篇文章-你刚刚帮我省去了很多打字的麻烦!
const hotspot = document.querySelector(".hotspot-active");
const id = Array.from(hotspot.classList).find(Number);

if (id) {               
  document.getElementById(id).classList.add("locator-active");
}