单击div上的Jquery启用按钮并显示相应的项目

我有三个主要的div和禁用按钮 . 当点击Div1时,它将显示另外两个div . (Div4,Div5)我需要在点击Div2,Div3,Div4和Div5时启用按钮 .

FIDDLE LINK

$(document).ready(function() {
  $('.row .item').click(function() {
    $('.row').find('.item').removeClass('selected');
    $(this).addClass('selected');

    if ($(".item-expand").hasClass("selected")) {
      $(".sub-item-container").removeClass('d-none');
    } else {
      $(".sub-item-container").addClass('d-none');
    }
  });

  $('.sub-item-container .sub-item').click(function() {
    $('.sub-item-container').find('.sub-item').removeClass('selected');
    $(this).addClass('selected');

  });
});
.item {
  width: 100px;
  height: 100px;
  background-color: blue;
  color: #fff;
  margin: 0 20px;
  cursor: pointer;
}

.sub-item {
  width: 100px;
  height: 100px;
  background-color: green;
  color: #fff;
  margin: 0 20px;
  cursor: pointer;
}

.row {
  margin-bottom: 20px;
}

.selected {
  background-color: red;
  border: 3px solid #000;
}

.showitem {
  background-color: yellow;
  padding: 20px;
  margin: 5px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-4 item item-expand">
      Div 1
    </div>

    <div class="col-md-4 item">
      Div 2
    </div>

    <div class="col-md-4 item">
      Div 3
    </div>
  </div>

  <div class="sub-item-container row d-none">
    <div class="col-md-4 sub-item">
      Div 4
    </div>

    <div class="col-md-4 sub-item">
      Div 5
    </div>
  </div>

  <button class="btn btn-primary" disable>Click</button>


  <div class="row mt-5">
    <div class="showitem div2">
      Show this div when Div 2 is selected and button clicked.
    </div>

    <div class="showitem div3">
      Show this div when Div 3 is selected and button clicked.
    </div>

    <div class="showitem div4">
      Show this div when Div 4 is selected and button clicked.
    </div>

    <div class="showitem div5">
      Show this div when Div 5 is selected and button clicked.
    </div>
  </div>
</div>

image

一旦选择了一个div(div2,div3,div4或div5),点击按钮我想显示相应的div .

Image

回答(1)

3 years ago

按照这个fiddle . 您可以在 data 属性中存储元素的类名,或者您可以调用它 . 并用 class 操纵元素

$("button").click(function(){
    var item = $(".selected").attr("data");
    $(".showitem").hide();
    $("."+item).show();
})