如果文本为0,则JavaScript隐藏DIV标记
我有个问题。如果文本为0,我尝试隐藏div。我的代码是:如果文本为0,则JavaScript隐藏DIV标记,javascript,jquery,trim,Javascript,Jquery,Trim,我有个问题。如果文本为0,我尝试隐藏div。我的代码是: <script type="text/javascript"> $(function () { if ($(".notification-counter").text() == "0") { $(".notification-counter").hide(); $(".notification-container").hide(); }
<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>
$(函数(){
如果($(“.notification counter”).text()=“0”){
$(“.notification counter”).hide();
$(“.notification container”).hide();
}
});
尝试使用parseInt()
将您的比较变成数字与数字,而不是比较文本字符串(这可以缓解空白问题。
$(function () {
if (parseInt($(".notification-counter").text()) == 0) {
//$(".notification-counter").hide();
$(".notification-container").hide();
}
});
使用修剪,因为有空白
尝试以下操作:而不是.text()put.html()
只要删除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
如果($.trim($(“.notification counter”).text())===“0”)
您在DIV中有一个空格,请尝试注意,.text()
将只返回第一个匹配元素的文本,因此如果您有多个。通知计数器
元素,您必须在循环中检查它,并仅隐藏相应的容器为什么拒绝投票?我用小提琴给出了正确答案!!看起来好像有人对所有内容进行了拒绝投票..:/在计数器的ide中,您已经隐藏了容器。但是也就是说,这比修剪文本imho.@A.Wolff更具可读性。很好的一点…我注释掉了隐藏计数器行。欢迎使用。如果可能,最好对您的代码做一些解释,并链接到相关文档——这将有助于ain声誉和特权!更多提示,请查看。谢谢!
$(function() {
if ($(".notification-counter").html() == "0") {
$(".notification-counter").hide();
$(".notification-container").hide();
}
});
$(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