如何使用不同的ID多次调用同一函数

时间:2019-05-21 10:39:03

标签: jquery html

我试图使用下拉值多次调用同一函数。它仅对第一个有效,其余两个无效。我该怎么解决?

<button id="jointables" onclick="joinsTable()" class="btn btn-success report-btn" data-toggle="collapse">
  <i class="glyphicon glyphicon-random"></i>
  &nbsp;&nbsp;Join Tables
  <div id="myDropdown" class="dropdown-content">
    <a href="#" class="table">One Table Join</a>
    <a href="#" class="table">Two Table Join</a>
    <a href="#" class="table">Three Table Join</a>
  </div>
</button>
$('.table').click(function(e) {
  $(".collapse").toggle();

2 个答案:

答案 0 :(得分:1)

尝试一下

<div class="dropdown">
   <button id="jointables" onclick="joinsTable()" class="btn btn-success report-btn" data-toggle="collapse">
   <i class="glyphicon glyphicon-random"></i>
  </button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#" class="table">One Table Join</a>
    <a href="#" class="table">Two Table Join</a>
    <a href="#" class="table">Three Table Join</a>
  </div>
 </div>

$(document).on('click', '.dropdown-content a', function () {
    alert($(this).text());
})

答案 1 :(得分:0)

由于您使用的是Bootstrap,请升级到4。不需要额外的jQuery,只需HTML中的正确属性即可。

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" rel="stylesheet" crossorigin="anonymous">

<div class='dropdown'>
<button class="btn btn-success btn-lg dropdown-toggle" data-toggle="dropdown">
  <i class="fas fa-random"></i>
  &nbsp;&nbsp;Join Tables</button>
  <div class="dropdown-menu">
    <a href="#" class="dropdown-item table">One Table Join</a>
    <a href="#" class="dropdown-item table">Two Table Join</a>
    <a href="#" class="dropdown-item table">Three Table Join</a>
  </div>
</div>
  
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>