javascript - 如果按钮没有显示,请更改按钮的文本?

标签 javascript jquery html button checkbox

我有一个用于数据库搜索字段的复选框列表。当有人单击复选框时,它将显示一个按钮,其中包含该复选框标签中的文本。但是,我需要该按钮在不可见时具有空文本(如果有人单击复选框来隐藏该按钮)。

这是我的代码:

$(document).ready(function() {
  $('#locationAll').click(function() {
    var value = $('#locationAll').parent().text();
    $('#location-all-button').html(value + " ×").toggle('fast');
  });
});

$(document).ready(function() {
  $('.search-popup').click(function() {
    $(this).hide('fast');
  });
  if ($('.search-popup').css('display') == 'none') {
    $(this).text("");
  };
});
button {
  background-color: lightgray;
  border-radius: 20px;
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox" value="all" id="locationAll" />All
</label>
<br>
<br>
<button class="search-popup btn" id="location-all-button"></button>

出于某种原因,我无法使按钮在此处示例的复选框之前保持隐藏状态,但这在我的完整代码中不是问题。如果您需要更多信息,请告诉我我可能错过了一些东西。

最佳答案

好吧,我改变了一些东西。我为任何遵循我很快制定的命名方案的复选框做了这项工作。方案是按钮的id=“按钮-”+id。此外,我还隐藏了所有带有类的按钮,以设置它们的默认状态。

$(document).ready(function()
{
    \\change to allow all checkboxes to trigger
    $('input[type=checkbox]').click(function()
    {
       \\change the id so it match a button when add "button-" to the start
       \\this allows me to target the matching button with any chechbox 
       $('#button-'+$(this).attr('id')).toggle('fast');
    });
    $('.search-popup').click(function()
    {
       $(this).hide('fast');
       \\ sets the check box to false so it not checked when you close it
       $("#"+$(this).text().replace(" &ensp;&times;","")).attr('checked', false);
    });

   \\hides all buttons right form the start
   $('button.search-popup').each(function()
   {
       $(this).hide();
   });
});

<label>
   <input type="checkbox" value="all" id="All" />All
</label>
<br>
<br>
<button class="search-popup btn" id="button-All">All &ensp;&times;</button>

现在,如果您想在复选框更改状态时创建和删除按钮,您可以添加一个 if 状态,意思是检查具有匹配 id 的按钮是否存在,!$(tag).size() 。

关于javascript - 如果按钮没有显示,请更改按钮的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066966/

相关文章:

javascript - 在另一个可观察值之后使用 fork join 的更好方法

javascript - D3js map 上的圆圈 : Projection Issue?

jquery - 使固定的div水平滚动,并在页面最大化时返回中心

javascript - 防止Rails/html5游戏App作弊(Rails 3.2/html5/javascript)

javascript - 获取查询查找的属性

javascript - 无法从 javascript 中的对象获取属性,但可以在记录其父级时将其打印到控制台

jquery - 如何使用 jquery 打印动态 div html 元素

javascript - 通过从 URL 获取百分比在 Django 中添加进度栏

html - 我是编码新手,我不太确定为什么我的 index.html 无法正确加载。

html - Bootstrap 4 中旋转木马图像顶部意外的白色背景