在jquery中只有button有值时才显示button

Show button only when there is a value in button in jquery?

本文关键字:button 显示 jquery      更新时间:2023-09-26

我有一个这样的按钮:

  <button> {{ pages.first }}</button>
 <button>{{ pages.last }}</button>

有时值{{pages。首先}}可以为空,有时不能。如果值为空,我根本不想显示按钮。我试过这个,但是这个隐藏按钮总是:

if(!$('button').val()){
    $('button').hide();
}
else {
    $('button').show();
}

我做错了什么?

我的按钮在代码中是这样的:

<button class="next_prev" onclick="" disabled>{% get_pages %} {{ pages.next }}</button> <button class="next_prev" onclick="" id="last_button" disabled>{% get_pages %} {{ pages.last }}</button>

您需要使用text()而不是val()。如果有多个按钮,你需要遍历这些按钮。

试试这个

 $.each($("button"),function(){  //in case of multiple button
  if(!$(this).text()){
    $(this).hide();
   }
  else {
    $(this).show();
  }
})

working fiddle here

text代替val可以达到目的

if(!$('button').text()){
   $('button').hide();
}
else {
  $('button').show();
}

使用.each()遍历并检查所有按钮:Sample

$.each($("button"),function(){
  if(!$(this).text().trim()){
     $('this).hide();
  }
  else {
     $(this).show();
  }
});

您的代码.val()将适用于<input type="submit"/>按钮