如何阻止其他功能干扰单击事件?

时间:2019-03-26 21:04:57

标签: javascript

我试图基于单击事件显示三个单独的内容。这是可行的,但是如果用户依次单击多个按钮,则会同时显示两个内容。

我对JS的了解有限。我知道另一个“其他”条件可能会对我有帮助,但是当我添加它时,整个功能将停止工作。

我希望一次只能显示一个内容选项。有没有一种方法可以在函数声明中添加其他条件来执行此操作?谢谢您的帮助。

.container-top {
  display: flex;
  flex-direction: row;
  width: 100%;
  justify-content: space-between;
}

.tab {
  border: 2px solid #DCDCDC;
  background-color: #fff;
  padding: 1rem;
  width: 33%;
  text-align: center;
  text-transform: uppercase;
}
<div class="container-top">

  <button onclick="productDrop()" class="tab" >
    <span class="tab-title">Product description</span>
  </button>

  <button onclick="financeDrop()" class="tab" id="finance">
    <span class="tab-title">Interest-free finance</span>
  </button>


  <button onclick="deliveryDrop()"class="tab" id="delivery">
    <span class="tab-button">Delivery and returns</span>
  </button>

</div>


<div id="productBody">
Product
</div>

<div id="financeBody">
Finance 
</div>

<div id="deliveryBody">
Delivery 
</div>

<script>
function productDrop() {
  var x = document.getElementById("productBody");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

function financeDrop() {
  var x = document.getElementById("financeBody");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

function deliveryDrop() {
  var x = document.getElementById("deliveryBody");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

</script>

1 个答案:

答案 0 :(得分:1)

您想得太多。让我们巩固并实现相同的目标:

const blah = document.getElementById('displayArea');

blah.innerHTML = 'Product'; // First Default.

drop = (id) => {
  blah.innerHTML = id;
}
.container-top {
  display: flex;
  flex-direction: row;
  width: 100%;
  justify-content: space-between;
}

.tab {
  border: 2px solid #DCDCDC;
  background-color: #fff;
  padding: 1rem;
  width: 33%;
  text-align: center;
  text-transform: uppercase;
}
<div class="container-top">

  <button onclick="drop('Product')" class="tab" autofocus>
    <span class="tab-title">Product description</span>
  </button>

  <button onclick="drop('Finance')" class="tab">
    <span class="tab-title">Interest-free finance</span>
  </button>


  <button onclick="drop('Delivery')"class="tab">
    <span class="tab-button">Delivery and returns</span>
  </button>

</div>


<h1 id="displayArea"></h1>

相关问题