单击第一个元素显示第一个模态,单击第二个元素显示第二个模态

时间:2017-05-22 14:00:47

标签: javascript jquery

喜欢在线程中。我想通过点击第一个&t 39来显示第一个模态。接下来我想通过点击第二个模式来显示第二个模态。等等。如何使用不在ids中的课程?这是一个例子。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  <table>
    <tr>
      <td>td</td>
      <td>td</td>
      <td>td</td>
    </tr>

    <tr>
      <td>td</td>
      <td>td</td>
      <td>td</td>
    </tr>
  </table>

  <div class="modal">modal1</div>
  <div class="modal">modal2</div>
  <div class="modal">modal3</div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>

https://jsfiddle.net/znzjeaq4/

2 个答案:

答案 0 :(得分:0)

JSFiddle

您想要为您的TD和模态分配ID:

<table>
    <tr>
      <td id="1">td</td>
      <td id="2">td</td>
      <td id="3">td</td>
    </tr>

    <tr>
      <td id="4">td</td>
      <td id="5">td</td>
      <td id="6">td</td>
    </tr>
  </table>

  <div class="modal" id="m1">modal1</div>
  <div class="modal" id="m2">modal2</div>
  <div class="modal" id="m3">modal3</div>
  <div class="modal" id="m4">modal4</div>
  <div class="modal" id="m5">modal5</div>
  <div class="modal" id="m6">modal6</div>

然后,在TD上点击,获取ID,然后将该ID用于模态:

$("td").click(function() {
    var id = $(this).attr("id");
  $("#m" + id).show();
})

答案 1 :(得分:0)

<强> CSS

所以,第一个例子是使用nth-child在多个类元素中进行选择,然后:active /:focus以在点击时启动一个动作。

&#13;
&#13;
.modal {
  float: left;
  width: 100px;
  height: 100px;
  background: #ccc;
  margin-right: 20px;
  cursor: pointer;
}

.modal:nth-child(1):active,
.modal:nth-child(1):focus {
  background: green;
}
.modal:nth-child(2):active,
.modal:nth-child(2):focus {
  background: blue;
}
.modal:nth-child(3):active,
.modal:nth-child(3):focus {
  background: red;
}
&#13;
<div class="modal"></div>
<div class="modal"></div>
<div class="modal"></div>
&#13;
&#13;
&#13;

<强> JS

使用JavaScript,您可以选择每个类,如果它没有ID,可以选择类似于CSS的第n个孩子,即('modal')[0]。因此,document.getElementsByClassName抓取所有.modal div,('modal')[0]('modal')[1]('modal')[3]将是您如何选择每个(从&#34; 0&#34; as开始)你要计算的第一个元素。)JS的例子可以更详细,但这只是关注&#34;点击这个,做那个......&#34; (就像您点击以启动相关模态一样。)

&#13;
&#13;
var modal_001 = document.getElementsByClassName('modal')[0];
var modal_002 = document.getElementsByClassName('modal')[1];
var modal_003 = document.getElementsByClassName('modal')[2];

modal_001.addEventListener('click', function() {
  this.style.background = "green";
});

modal_002.addEventListener('click', function() {
  this.style.background = "blue";
});

modal_003.addEventListener('click', function() {
  this.style.background = "red";
});
&#13;
.modal {
  float: left;
  width: 100px;
  height: 100px;
  background: #ccc;
  margin-right: 20px;
  cursor: pointer;
}
&#13;
<div class="modal"></div>
<div class="modal"></div>
<div class="modal"></div>
&#13;
&#13;
&#13;