Because each .landmark-button
looks to be in the same order as its related .landmark-info
, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
(因为每个.landmark-button
看起来都与其相关的.landmark-info
顺序相同,所以您可以将两个集合放入一个数组中,然后单击一个集合,只需在另一个数组中找到具有相同索引的元素:)
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
(这根本不依赖于ID-随意将其从HTML中完全删除以使其杂乱无章,因为由于它们没有被用作选择器,因此它们没有任何作用。)
Live snippet:
(现场摘要:)
const buttons = [...$('.landmark-button')]; const infos = [...$('.landmark-info')]; $(".landmark-button").click(function() { const i = buttons.indexOf(this); $(infos[i]).addClass('active-info'); });
.active-info { background-color: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="landmark-wrapper"> <div class="page-content landmark"> <div class="heading span-after"> <span>Arch of Triumph</span> </div> <div class="landmark-button" id="arch-of-triumph-button">click</div> </div> </div> <div class="landmark-wrapper"> <div class="page-content landmark"> <div class="heading span-after"> <span>Romanian Athenaeum</span> </div> <div class="landmark-button" id="romanian-athenaeum-button">click</div> </div> </div> ---------------------------------------------------------- <div class="landmarks-info-wrapper"> <div class="landmark-info" id="arch-of-triumph-info"> <div class="info-landmark section"> <span class="landmark-title">Arch of Triumph</span> <span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span> </div> </div> <div class="landmark-info" id="romanian-athenaeum-info"> <div class="info-landmark section"> <span class="landmark-title">The Romanian Athenaeum</span> <span class="landmark-coord">44.4413°N 26.0973°E</span> </div> </div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button
part of it, and then select it concatenated with -info
:
(较旧的答案,但不知道HTML:您可以提取所单击按钮的ID,将其button
部分-info
,然后将其与-info
连接起来:)
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.
(不过,考虑到HTML,可能会有一个更优雅的解决方案。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…