隐藏div,除非它有来自onclick

时间:2018-03-26 03:45:57

标签: javascript jquery onclick

如果有来自点击.modal-item的来源,我如何只显示.modal容器内的.item div?

示例:如果我单击了第一个项目,则只显示#item-img div,因为它是唯一从函数接收源的div。 #item-text#item-sub-text都将保留hidden,因为它们没有来源。



$(".container").on("click", ".item", function() {
  var t = $(this).closest(".item");
  $("#item-text").text(t.find(".item-text").text());
    $("#item-sub-text").text(t.find(".item-sub-text").text());
  	var a = t.find(".item-img").attr("src");
	$("#item-img").css("background-image", 'url("' + a + '")'); 
});

.body {
  display: flex;
}
.container,
.modal {
  display: flex;
  flex-direction: column;
  padding: 20px;
}
.container {
  border: 1px solid blue;
}
.modal {

  background: #eee
}
.item,
.modal-item {
  width: 50px;
  height: 50px;
  cursor: pointer;
  border: 1px solid;
}
.item-img {
  height: 50px;
  width: 50px;
  border: none;
}
#item-img {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
  <div class="container">
    <div class="item">
      <img class="item-img" src="https://www.oysterdiving.com/components/com_easyblog/themes/wireframe/images/placeholder-image.png">
      <div class="item">
        <p class="item-text"></p>
      </div>
      <div class="item">
        <p class="item-sub-text"></p>
      </div>
    </div>
  </div>
  <div class="container">
    <div class="item">
      <img class="item-img" src="">
      <div class="item">
        <p class="item-text">Text</p>
      </div>
      <div class="item">
        <p class="item-sub-text"></p>
      </div>
    </div>
  </div>
  <div class="container">
    <div class="item">
      <img class="item-img" src="">
      <div class="item">
        <p class="item-text"></p>
      </div>
      <div class="item">
        <p class="item-sub-text">Sub</p>
      </div>
    </div>
  </div>
  <div class="modal">
    <div class="modal-item" id="item-img"></div>
    <div class="modal-item" id="item-text">
      <p></p>
    </div>
    <div class="modal-item" id="item-sub-text">
      <p></p>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用hide()show()函数jQuery

function checkShowHide(text, ele) {
  if (text !== '') {
    $(ele).show();
    $(ele).text(text);
  } else {
    $(ele).hide();
  }
}
$(".container").on("click", ".item", function() {
  var t = $(this).closest(".item");
  var itemText = t.find(".item-text").text();
  var itemSubText = t.find(".item-sub-text").text()
  var itemBG = t.find(".item-img").attr("src");
  checkShowHide(itemText, '#item-text');
  checkShowHide(itemSubText, '#item-sub-text');

    var a = t.find(".item-img").attr("src");
  if (a !== '') {
    $("#item-img").show();
    $("#item-img").css("background-image", 'url("' + a + '")'); 
  } else {
    $("#item-img").hide();
  }

});

这是我的解决方案。您可以登录我的codepen:https://codepen.io/titan_dl_1904/pen/pLWrxg