You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击c-1按钮时如何激活所有同Data ID内容及跨Div调用

Solution for Activating Shared Content Across Divs

Hey there! Let's get this working properly for you. First, a quick heads-up: your current HTML has duplicate id="tab-1" elements, which is invalid in HTML — IDs must be unique across the entire page. That's why your original code only activates the first matching element, not the one in the second div. Instead, we'll use shared data attributes to group related content, which works seamlessly across different container divs.

Step 1: Fix the HTML Structure

We'll replace duplicate IDs with a data-tab attribute (you can name this anything, but it's clear what it's for). Keep the button's data-id to target these groups:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mark-container">
  <div class="c-1" data-id="tab-1">
    <p>for 1 btn</p>
  </div>
  <div class="c-1-details" data-tab="tab-1">
    <p>for 1 details</p>
  </div>
</div>
<div class="second-mark">
  <ul>
    <li class="tab-corner" data-tab="tab-1">tab-1-btn</li>
  </ul>
  <div class="tab-content" data-tab="tab-1">
    tab-1-content
  </div>
</div>

Step 2: Update the JavaScript Logic

Now we'll modify the click handler to target all elements with the matching data-tab value, regardless of which div they're in. We'll also clean up some typos in your original code (you missed a dot in $("c-1-details")):

$('.c-1').click(function() {
  // Get the target group from the button's data attribute
  var targetTab = $(this).attr('data-id');
  
  // Remove active state from all .c-1 buttons and all tab content
  $('.c-1').removeClass('active');
  $('[data-tab]').removeClass('active');
  
  // Add active state to the clicked button
  $(this).addClass('active');
  
  // Add active state to ALL elements with the matching data-tab value
  $('[data-tab="' + targetTab + '"]').addClass('active');
});

Key Notes:

  • Why no duplicate IDs? Browsers only ever return the first element with a matching ID when using $("#tab-1"), so your second content div would never be activated otherwise.
  • Cross-div targeting: Using $('[data-tab="' + targetTab + '"]') selects every element with that data attribute, no matter which parent div it lives in.
  • CSS for visibility: Don't forget to add CSS to hide non-active content, like:
[data-tab].active {
  display: block;
}
[data-tab] {
  display: none;
}
.c-1.active {
  /* Style for active button, e.g., background color */
  background-color: #eee;
}

内容的提问来源于stack exchange,提问作者xx_secretpooh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:25:40