如果文本为 0,JavaScript 隐藏 DIV 标记

JavaScript hide DIV tag if text is 0

本文关键字:隐藏 DIV 标记 JavaScript 文本 如果      更新时间:2023-09-26

>我有一个问题。如果文本为 0,我正在尝试隐藏div。我的代码是:

<script type="text/javascript">
    $(function () {
        if ($(".notification-counter").text() == "0") {
            $(".notification-counter").hide();
            $(".notification-container").hide();
        }
    });
</script>
<div class="dropdown nav-search pull-right <?php $this->_c('login') ?>">
    <a href="../pm/" class="dropdown-toggle"><i class="fa fa-inbox"></i>
        <div class="notification-container">
            <div class="notification-counter">
                <?php
                      jimport( 'joomla.application.module.helper' );
                      $module = JModuleHelper::getModule('mod_uddeim_simple_notifier');
                      echo JModuleHelper::renderModule( $module, $attribs );
                ?>
            </div>
        </div>                                  
    </a>    
</div>

但它不起作用...有人可以帮忙吗?感谢您的回答!

尝试使用 parseInt() 将比较设置为数字与数字,而不是比较文本字符串(它减轻了空格问题。吉斯菲德尔

$(function () {
    if (parseInt($(".notification-counter").text()) == 0) {
        //$(".notification-counter").hide();
        $(".notification-container").hide();
    }
});

使用修剪,因为有空格

小提琴

$(function () {
    if ($.trim($(".notification-counter").text()) == "0") {
        $(".notification-counter").hide();
        $(".notification-container").hide();
    }
});

只需删除 0 周围的引号,它就可以正常工作。

$(function () {
    if ($(".notification-counter").text() == 0) {
        $(".notification-counter").hide();
        $(".notification-container").hide();
    }
});

附加信息:由于这里的许多人似乎不清楚,这里有一个小帮手:在控制台中尝试此操作

 //hit F12 to view the console
var counter = $(".notification-counter");
var container = $(".notification-container");
console.log(container.text(), container.html());
console.log(container.text() == 0,container.text() == "0");
//true, false
console.log(typeof 0, typeof "0");
//number, string

JSFiddle

var notificationCounter = $('.notification-counter');
if (notificationCounter.text().trim() === '0') {
  notificationCounter.closest('.notification-container').hide();
}

试试这个:代替 .text() 放 .html()

$(function() {
  if ($(".notification-counter").html() == "0") {
    $(".notification-counter").hide();
    $(".notification-container").hide();
  }
});