我有一个用于数据库搜索字段的复选框列表。当有人单击复选框时,它将显示一个按钮,其中包含该复选框标签中的文本。但是,我需要该按钮在不可见时具有空文本(如果有人单击复选框来隐藏该按钮)。
这是我的代码:
$(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("  ×","")).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  ×</button>
现在,如果您想在复选框更改状态时创建和删除按钮,您可以添加一个 if 状态,意思是检查具有匹配 id 的按钮是否存在,!$(tag).size() 。
关于javascript - 如果按钮没有显示,请更改按钮的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066966/