javascript - 如果相应的元素 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" />
解决方案
您可以用于
$(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');
}
}
});
推荐阅读
- apache-camel - 需要使用 Camel-Bindy 格式将字符串转换为浮点变量
- asp.net-core - 使用 On-Premise Active Directory (NOT AZURE AD) 作为 Identity Server 4 的身份提供程序存储
- reactjs - 使用钩子设置具有相同值的状态会导致重新渲染?
- python - 获取python中列表的所有排列而不重复?
- javascript - NetSuite 报告附件
- machine-learning - 在 Flux-Julia 中使用 LSTM 对完整序列进行建模
- python - 当所有句子的关键字都包含在字典中时,如何将句子与字典关联?
- ruby-on-rails - 在特定文件夹上安装 Ruby Gem + 依赖项并运行该安装
- ignite - 如果未启用持久性,apache 是否会点燃对 work/marshaller 目录的写入?
- linux - 操作系统如何知道进程何时应该处于阻塞状态?