[英]Javascript: How to hide div if Label inside is empty
如果其中的标签没有要显示的内容,我想用class =“ form-group”隐藏div,这是我的html代码:
echo'<div class="form-group">';
echo'<label for="exampleInputFile" class="tbh">'.$query2['req_1'].'</label>';
echo'<input type="file" name="my_image" accept="image/*" id="exampleInputFile"> ';
echo'</div>';
我的javascript在这里:
<script type="text/javascript">
if($('label.tbh:empty')){
$('div.form-group').hide();
}
</script>
还有其他方法吗? 在我的代码中,它似乎不起作用。 先谢谢您的帮助。
使用.text()
是更安全的选择。 如果标签为空,则.text()
将返回一个空字符串,并将其取反将得到true
。 请参考以下示例的交互式代码段。 我将相关代码放在按钮单击处理程序中,以证明单击它后它可以工作。
$('button').click(function () { if (!$('.tbh').text()){ $('.form-group').hide(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="exampleInputFile" class="tbh"></label> <input type="file" name="my_image" accept="image/*" id="exampleInputFile"></div> <button>Click to hide</button>
尝试这个:
if($('label.tbh').html() == ""){
$('div.form-group').hide();
}
您可以这样做:
/* Be sure that your dom is loaded */
$( document ).ready(function() {
/* Checking that the label is empty */
if($("label").html().length == 0) {
$('div.form-group').hide();
}
});
您也可以使用size()
代替length
。
如果您使用的是jQuery,则可以通过以下方式实现:
$("div.form-group label.tbh:empty").parent().hide();
这是在document.ready
回调内部执行的正确方法:
$(document).ready(function(){
$("div.form-group label.tbh:empty").parent().hide()
});
要包括jQuery,请添加
echo '<script src="https://code.jquery.com/jquery-3.1.1.js"></script>';
脚本的开头。
但是似乎您正在使用PHP或在后端使用类似工具? 如果是这样,您可以在服务器端代码上执行以下操作:
if(strlen($query2['req_1']) == 0)
{
echo'<div class="form-group">';
echo'<label for="exampleInputFile" class="tbh">'.$query2["req_1"].'</label>';
echo'<input type="file" name="my_image" accept="image/*" id="exampleInputFile"> ';
echo'</div>';
}
在这种情况下,您不会将不需要的数据传输到客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.