更新引导拆分按钮文本并使用下拉按钮功能

Update Bootstrap split button text and function with dropdown button

本文关键字:按钮 功能 文本 拆分 更新      更新时间:2023-09-26

我有一个拆分按钮下拉菜单;最初,按钮的文本是"网站",单击后不会执行任何操作。我想让它从下拉列表中单击哪个选项,该选项的文本和onClick功能都会在按钮中更新。

例如,我有一个带有"网站"文本的拆分按钮,下拉菜单中有"谷歌","雅虎","必应"作为选项。每个选项都指向各自的网站。如果单击"Google",我想将"Webites"替换为"Google"(或自定义文本),现在单击拆分按钮时,它也会转到Google的网站。

<div class="btn-group">
  <button type="button" class="btn btn-sm btn-danger">Websites</button>
  <button onClick="updateDropdown()" type="button" class="btn btn-sm btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="http://www.google.com/">Google</a></li>
    <li><a href="http://www.yahoo.com/">Yahoo</a></li>
    <li><a href="http://www.bing.com/">Bing</a></li>
  </ul>
</div>

JSFiddle Demo

$('.dropdown-menu a').on('click', function(e){
    e.preventDefault();
  var anchor = $(e.currentTarget);
  var href = anchor.attr('href');
  var text = anchor.text();
    var button = anchor.closest('.btn-group').find('button:first-child');
  button.attr('data-url', href);
  button.text(text);
  button.on('click', gotoUrl);
});
function gotoUrl(e){
e.preventDefault();
//use window.open because we can't open these urls in jsfiddle.
window.open($(e.currentTarget).attr('data-url'));
//Maybe this is what you want in your site.
//window.location.href = $(e.currentTarget).attr('data-url')
}

这是一个工作 js 小提琴。http://jsfiddle.net/dattaproffs/bjf21pxj/1/

我不知道 updateDropdown 做了什么,所以我只是把它留在那里。