更改按钮文本的值

时间:2016-12-19 10:26:38

标签: javascript jquery html jsp

<div>
<button type="button" style="width:250px;"onclick="loadMenu('menu_${bookings.bookingId}')" class="btn btn-default btn-sm">View Items</button>
</div>

<div id="menu_${bookings.bookingId}" style="display: none;">
    ${bookings.products}
</div>

我想在点击该按钮时将查看项的值更改为隐藏项

我的脚本

function loadMenu(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
{
   e.style.display = 'none';
   }
    else{
       e.style.display = 'block';
    }
} 

2 个答案:

答案 0 :(得分:1)

首先,您应该使用不显眼的事件处理程序,而不是过时的on*事件属性。

从那里,您可以使用this关键字来引用点击的按钮,并根据其当前值切换其文本。试试这个:

&#13;
&#13;
document.querySelectorAll('.booking-toggle').forEach(function() {
  this.addEventListener('click', function(e) {
    var id = e.target.getAttribute('data-bookingid');
    var booking = document.getElementById(id);
    booking.style.display = booking.style.display == 'block' ? 'none' : 'block';
    e.target.innerText = e.target.innerText == 'View Items' ? 'Hide Items' : 'View Items';
  });
});
&#13;
<div>
  <button type="button" style="width:250px;" data-bookingid="bookingId_1" class="btn btn-default btn-sm booking-toggle" id="foo">View Items</button>
</div>

<div id="bookingId_1" style="display: none;">
  ${bookings.products}
</div>
&#13;
&#13;
&#13;

或者在jQuery中:

&#13;
&#13;
$('.booking-toggle').click(function() {
  var $btn = $(this);
  $('#' + $btn.data('bookingid')).toggle();
  $btn.text(function(i, t) {
      return t == 'View Items' ? 'Hide Items' : 'View Items';
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button type="button" style="width:250px;" data-bookingid="bookingId_1" class="btn btn-default btn-sm booking-toggle" id="foo">View Items</button>
</div>

<div id="bookingId_1" style="display: none;">
  ${bookings.products}
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

清除演示和代码:

HTML

<button  id="button" href="#">Show/Hide</button>
<div id="item">Item</div>

JS:

$( "#button" ).click(function() {
$( "#item" ).toggle();
});

用按钮替换链接:

http://jsfiddle.net/BQUyT/

另一个例子

http://www.randomsnippets.com/2011/04/10/how-to-hide-show-or-toggle-your-div-with-jquery/