多个按钮和同一类的多个模态,在单击时显示一个模态

时间:2018-04-21 19:43:49

标签: jquery

我需要在单击按钮时显示模态,我有多个按钮和同一类的模态。我写了一个小的jQuery代码,但当我点击任何按钮时,所有模态都会立刻出现。我需要以某种方式在单击相应按钮时仅显示相应的模态。但是再一次,我对所有按钮和模态都有相同的类。

我写了一个简化的演示,因此更清楚:

$("button").click(function() {
    $( ".modal" ).addClass("active");
});
body {
  padding: 20px;
}

.container {
  margin: 30px;
}

.modal {
    display: none;
    padding: 15px;
    position: relative;
    background: rgba(72, 72, 72, 0.95);
    color: #fff;
    width: 12vw;
    height: 80px;
    right: 0;
    margin: 10px;
    border-radius: 3px;
}

.modal.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button>open modal</button>
  <div class="modal">modal</div>
</div>

<div class="container">
  <button>open modal</button>
  <div class="modal">modal</div>
</div>

<div class="container">
  <button>open modal</button>
  <div class="modal">modal</div>
</div>

感谢。

1 个答案:

答案 0 :(得分:0)

$(&#34; .modal&#34;)选择器选择所有模态并为其添加活动类,因此您必须像我所做的那样进行更改

&#13;
&#13;
$("button").click(function(e) {
    $( "."+e.target.id).addClass("active");
});
&#13;
body {
  padding: 20px;
}

.container {
  margin: 30px;
}

.modal {
    display: none;
    padding: 15px;
    position: relative;
    background: rgba(72, 72, 72, 0.95);
    color: #fff;
    width: 12vw;
    height: 80px;
    right: 0;
    margin: 10px;
    border-radius: 3px;
}

.modal.active {
  display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button id="button1">open modal</button>
  <div class="button1 modal">modal</div>
</div>

<div class="container">
  <button id="button2">open modal</button>
  <div class="button2 modal">modal</div>
</div>

<div class="container">
  <button id="button3">open modal</button>
  <div class="button3 modal">modal</div>
</div>
&#13;
&#13;
&#13;