如何使用jquery更改html按钮标签的文本

时间:2018-05-07 22:43:51

标签: javascript jquery html

我有一个html代码,我想使用jQuery更改文本值...

<div class="dropdown">
   <button type="button" class="btn btn-secondary dropdown-toggle button-text" data-toggle="dropdown"><span>1395</span></button>
      <ul class="dropdown-menu">
         <li><a class="dropdown-item" href="#">1395</a></li>
         <li><a class="dropdown-item" href="#">1396</a></li>
         <li><a class="dropdown-item" href="#">1397</a></li>
         <li><a class="dropdown-item" href="#">1398</a></li>
         <li><a class="dropdown-item" href="#">1399</a></li>
      </ul>
</div>

不介意这个类(btn btn-secondary dropdown-toggle)用于bootstrap ......

2 个答案:

答案 0 :(得分:0)

尝试以下方式:

&#13;
&#13;
$('.dropdown-menu li').click(function(){
  $('button span').text($(this).find('a').text())
});
&#13;
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<div class="dropdown">
   <button type="button" class="btn btn-secondary dropdown-toggle button-text" data-toggle="dropdown"><span>1395</span></button>
      <ul class="dropdown-menu">
         <li><a class="dropdown-item" href="#">1395</a></li>
         <li><a class="dropdown-item" href="#">1396</a></li>
         <li><a class="dropdown-item" href="#">1397</a></li>
         <li><a class="dropdown-item" href="#">1398</a></li>
         <li><a class="dropdown-item" href="#">1399</a></li>
      </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我在跨度上放了一个课程,以便轻松定位。然后我只在下拉菜单上放置一个点击绑定,处理任何项目的点击。单击任何项​​目时,它会找到最近的父下拉列表,然后在其中查找相关的嵌套选择元素并更改其文本。

&#13;
&#13;
$('.dropdown').on('click', '.dropdown-item', function(e){
  $(e.target).closest('.dropdown').find('.selection').text(e.target.innerText);
});
&#13;
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<div class="dropdown">
   <button type="button" class="btn btn-secondary dropdown-toggle button-text" data-toggle="dropdown"><span class="selection">1395</span></button>
      <ul class="dropdown-menu">
         <li><a class="dropdown-item" href="#">1395</a></li>
         <li><a class="dropdown-item" href="#">1396</a></li>
         <li><a class="dropdown-item" href="#">1397</a></li>
         <li><a class="dropdown-item" href="#">1398</a></li>
         <li><a class="dropdown-item" href="#">1399</a></li>
      </ul>
</div>
&#13;
&#13;
&#13;