如果条件为 jQuery,则隐藏跨度
Hide span if condition with jQuery
如果值 === 0,我想隐藏此跨度
<span class="amount">0</span>
然后我制作 mini-cart-remove.js
并添加到 header。
这是我的代码:
(function($) {
$(document).ready(function() {
if ($('.amount') === 0 ) {
$('.amount').hide();
}
});
})(jQuery);
但无法隐藏跨度
我做错了什么?
您必须获取范围内的文本,然后将其与 0 进行比较,为此您可以使用 .text()
if ($.trim($('.amount').text()) === '0' ) {
$('.amount').hide();
}
如果你想要有多个跨度,你将不得不遍历它们以隐藏它们
(function($) {
$(document).ready(function() {
$('.amount').each(function(){
if ($(this).text() === '0' ) {
$(this).hide();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="amount">0</span>
<span class="amount">1</span>
<span class="amount">2</span>
<span class="amount">3</span>
<span class="amount">4</span>
我之前就遇到过,因为我在 class 中设置了 display:block
所以,现在我从不在 class 中设置任何显示属性
只需使用 show() 或 hide() 来让元素显示或不显示
我之前遇到过它,因为我在 class 中设置了 display:block
所以,现在我从不在 class 中设置任何显示属性
只需使用 show() 或 hide() 来让元素显示或不显示
也许你设置了display:block;在你的 .amount class?
如果值 === 0,我想隐藏此跨度
<span class="amount">0</span>
然后我制作 mini-cart-remove.js
并添加到 header。
这是我的代码:
(function($) {
$(document).ready(function() {
if ($('.amount') === 0 ) {
$('.amount').hide();
}
});
})(jQuery);
但无法隐藏跨度
我做错了什么?
您必须获取范围内的文本,然后将其与 0 进行比较,为此您可以使用 .text()
if ($.trim($('.amount').text()) === '0' ) {
$('.amount').hide();
}
如果你想要有多个跨度,你将不得不遍历它们以隐藏它们
(function($) {
$(document).ready(function() {
$('.amount').each(function(){
if ($(this).text() === '0' ) {
$(this).hide();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="amount">0</span>
<span class="amount">1</span>
<span class="amount">2</span>
<span class="amount">3</span>
<span class="amount">4</span>
我之前就遇到过,因为我在 class 中设置了 display:block 所以,现在我从不在 class 中设置任何显示属性 只需使用 show() 或 hide() 来让元素显示或不显示 我之前遇到过它,因为我在 class 中设置了 display:block 所以,现在我从不在 class 中设置任何显示属性 只需使用 show() 或 hide() 来让元素显示或不显示
也许你设置了display:block;在你的 .amount class?