简体   繁体   English

使用 JQuery 当 Content == “0” 时隐藏 Div?

[英]Hide Div When Content == “0” Using JQuery?

Trying to write a script that checks the content of a div, and if that content is exactly 0 than it hides the div.尝试编写一个检查 div 内容的脚本,如果该内容恰好为 0,则它会隐藏 div。 This is for an inbox system so that the count only shows if you have a new message.这适用于收件箱系统,以便计数仅在您有新消息时显示。 This is what I wrote:这是我写的:

 var count = $('.count').val(); if (count == '0') { $('.count').hide(); } else { $('.count').show(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href='index.php?act=UserCP&CODE=alerts'> <span class="count"><.-- |new_alerts| --></span> alerts</a> <a href='index?php?act=Msg&CODE=01'> <span class="count"><!-- |new_msg| --></span> inbox</a>

Site Where the Problem is Occurring.发生问题的站点。

The <!--|new_msg| --> <!--|new_msg| --> <!--|new_msg| --> is part of the hosting site's user menu system. <!--|new_msg| -->是托管站点的用户菜单系统的一部分。 On the site it changes to a number, correlating to how many new alerts or new messages you have.在网站上,它会变成一个数字,与您有多少新警报或新消息相关。 Is this the reason?这是原因吗? The div has an actual number on the site, so it should read that right? div 在网站上有一个实际的数字,所以它应该读对吗?

I haven't figured out why but I have zero luck getting class selectors to work.我还没弄清楚为什么,但让 class 选择器工作的运气为零。 Try setting an id on the element.尝试在元素上设置一个 id。 And then...接着...

var count = $(document).getElementById("#countId").textContent;
if (count == '0') { 
    $(document).getElementById("#countId").style.display = 'none'; 
} 
else { 
    $(document).getElementById("#countId").style.display = ''; 
}

If you've multiple .count elements this is exactly what count variable will return [See The Next Code] .. And for sure it will not match 0 at all如果您有多个.count元素,这正是count变量将返回的内容[参见下一个代码] .. 并且肯定它根本不会匹配0

 $(document).ready(function(){ var count = $(".count").text().trim(); console.log(count); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="count">0</span> <span class="count">1</span> <span class="count">2</span>

The right way is to loop through the .count elements using .each or even .filter正确的方法是使用.each甚至.filter .count

 $(document).ready(function(){ $(".count").show(0).filter(function(){ return $(this).text().trim() == 0; }).hide(0); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="count">0</span> <span class="count">1</span> <span class="count">2</span>

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

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