如何使用jQuery选择列表中的右键?

时间:2019-05-21 13:18:42

标签: javascript jquery django templates

我有不同服务器的列表。因此,当单击按钮“连接”时,我想连接到该特定服务器。 如何使用jQuery选择正确的按钮?预先谢谢你!

{% for  server in servers%}
  {% if server.credential.user == user %}
    {% if server.credential.protocol == 'vnc' %}
      <a>
        <div class="p-l-20" id="server_details">
          <h4>{{server.name}}</h4>
          <h6>Hostname: {{server.hostname}}</h6>
          <h6>IP Address: {{server.ip}}</h6>
          <h6>Protocol: {{server.credential.protocol|upper}}</h6>
          <h6>User: {{server.credential.user}}</h6>
          <button type="button" >Connect</button>
        </div>
      </a>
    {% endif %}
  {% endif %}
{% endfor %}

1 个答案:

答案 0 :(得分:1)

首先,删除父<a>,因为您不能嵌套可点击的元素。其次,您将使用相同的id创建许多元素,这是无效的,因为它们在DOM中必须是唯一的。将server_details更改为一个类。

要实现所需的功能,请向button元素中添加事件处理程序。从那里,您可以遍历DOM以查找必要的服务器信息。在下面的示例中,我在IP地址周围添加了一个span类,您可以将其作为目标类来读取其text(),但是对于您要阅读的任何其他详细信息,模式都是相同的:

$('button').on('click', function() {
  var ip = $(this).closest('.server_details').find('.ip').text();
  console.log(ip);
});
.server_details {
  margin-bottom: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p-l-20 server_details">
  <h4>{{server.name1}}</h4>
  <h6>Hostname: {{server.hostname1}}</h6>
  <h6>IP Address: <span class="ip">{{server.ip1}}</span></h6>
  <h6>Protocol: {{server.credential.protocol1|upper}}</h6>
  <h6>User: {{server.credential.user1}}</h6>
  <button type="button">Connect</button>
</div>
<div class="p-l-20 server_details">
  <h4>{{server.name2}}</h4>
  <h6>Hostname: {{server.hostname2}}</h6>
  <h6>IP Address: <span class="ip">{{server.ip2}}</span></h6>
  <h6>Protocol: {{server.credential.protocol2|upper}}</h6>
  <h6>User: {{server.credential.user2}}</h6>
  <button type="button">Connect</button>
</div>