2017-05-10 109 views
2

我使用Bootstrap 3創建dropdown menus防止複製Bootstrap下拉菜單

它工作正常,但我有一個表的每一行完全相同的菜單。爲表中的每一行添加菜單對我來說似乎是一大浪費。此外,它阻止我爲菜單項分配唯一的ID。

是否有人熟悉如何使用Bootstrap下拉菜單在需要的地方分配單個菜單,以響應被點擊的項目?而不是在任何地方都可能需要重新定義菜單?

+0

您是否嘗試過使用AJAX來獲取信息? –

+0

@JorgePeña:這不會帶來任何好處,因爲我已經知道菜單中的確切命令。也許你不明白這個問題? –

+0

你想重複使用下拉菜單嗎? –

回答

1

這可能會幫助你,以達到你想要的

//save the selector so you don't have to do the lookup everytime 
 
$dropdown = $("#contextMenu"); 
 

 
$(".linktodisplay").click(function() { 
 
    //get row ID 
 
    var id = $(this).closest("tr").children().first().html(); 
 

 
    //move dropdown menu 
 
    $(this).after($dropdown); 
 

 
    
 
    //show dropdown 
 
    $(this).dropdown(); 
 
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> 
 
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet"/> 
 
<table id="myTable" class="table table-hover"> 
 
    <thead> 
 
     <tr> 
 
      <th>#</th> 
 
      <th>test 1</th> 
 
      <th>test 2</th> 
 
      <th>test 3</th> 
 
     </tr> 
 
    </thead> 
 
    <tbody> 
 
     <tr> 
 
      <td>1</td> 
 
      <td>Harry</td> 
 
      <td>sahil</td> 
 
      <td class="dropdown"> <a class="btn btn-default linktodisplay" data-toggle="dropdown" href="#"> 
 
        Click me 
 
       </a> 
 

 
      </td> 
 
     </tr> 
 
     <tr> 
 
      <td>2</td> 
 
      <td>sahil</td> 
 
      <td>nimish</td> 
 
      <td class="dropdown"> <a class="btn btn-default linktodisplay" data-toggle="dropdown" href="#"> 
 
        click me 2 
 
       </a> 
 

 
      </td> 
 
     </tr> 
 
     <tr> 
 
      <td>3</td> 
 
      <td>anu</td> 
 
      <td>potter</td> 
 
      <td class="dropdown"> <a class="btn btn-default linktodisplay" data-toggle="dropdown" href="#"> 
 
        click me 3 
 
       </a> 
 

 
      </td> 
 
     </tr> 
 
    </tbody> 
 
</table> 
 
<ul id="contextMenu" class="dropdown-menu" role="menu"> 
 
    <li><a tabindex="-1" href="#" class="itemlink1">Item1</a> 
 

 
    </li> 
 
    <li><a tabindex="-1" href="#" class="itemlink2">Item2</a> 
 

 
    </li> 
 
</ul>