简体   繁体   English

标签文本为空时如何隐藏Div?

[英]How can I hide a Div when text of a label is empty?

I am trying to hide the 'div' by checking if a label is empty. 我试图通过检查标签是否为空来隐藏'div'。 But Something went wrong. 但是出了点问题。 Below is the code I used. 下面是我使用的代码。

<script>
 function myfun(){
     if (document.getElementById('department').innerHTML=='') {
         document.getElementById('departmentdiv').style.display="none";
     }
 }
</script>
<body onload="myfun()">
  <div id="departmentdiv" class="row-fluid">
    <label>DEPARTMENT:</label>
    <label id="department"><?php if (!empty($_POST['department']))echo $_POST['department'];?></label>
  </div>
</body>

I am getting the POST[department] value from the a different page and assigned it to the label in this page. 我从另一个页面获取POST [部门]值,并将其分配给该页面中的标签。 I want to show the div only if the value is not null. 我只想在值不为null时显示div。 But, the problem is label doesn't show at all on this page even if its not null. 但是,问题是即使此标签不为null,标签也不会在此页面上显示。 Does anybody can help me out 有人可以帮我吗

May be you can try php empty function for validation .check if not empty post department then show : 可能是您可以尝试使用php空函数进行验证。如果邮政部门不为空,则显示:

<script>
    function myfun(){
    <?php if (empty($_POST['department'])){?>
        document.getElementById('departmentdiv').style.display="none";
    <?php }?>
    }
</script>

try something like this, 尝试这样的事情,

if (document.getElementById('department').innerHTML.length) {
    document.getElementById('departmentdiv').style.display="none";
}

if whitespace is causing problem then, 如果空格引起了问题,

 if (document.getElementById('department').innerHTML.trim().length) {
   document.getElementById('departmentdiv').style.display="none";
 }

使用isset()代替empty() :)

InnerHTML is working fine: InnerHTML运行正常:

 if (document.getElementById('department').innerHTML == '') {
     document.getElementById('departmentdiv').style.display = "none";
 }

Here is working demo 这是工作演示

As you can see in this JSFiddle , it does work. 正如您在此JSFiddle中所看到的,它确实起作用。 The problem must be with the PHP code. 问题必须出在PHP代码上。 You don't need to test with empty() , just output the variable. 您无需使用empty()进行测试,只需输出变量即可。 If there might be whitespace in the department, trim it before outputting 如果部门中可能有空白,请在输出之前对其进行trim

<div id="departmentdiv" class="row-fluid">
    <label>DEPARTMENT:</label>
    <label id="department"><?= trim($_POST['department']); ?></label>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM