簡體   English   中英

Javascript:如果內部標簽為空,如何隱藏div

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM