单击div上的jQuery Enable按钮并显示相应的项目

时间:2018-10-15 17:06:29

标签: javascript jquery html css

我有三个主要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 个答案:

答案 0 :(得分:1)

遵循此fiddle。您可以将元素的类名称存储在data属性中,也可以调用它。并使用带有class

的元素进行操作
$("button").click(function(){
    var item = $(".selected").attr("data");
    $(".showitem").hide();
    $("."+item).show();
})