Javascript 当为空时隐藏div并将类添加到另一个div
我们对产品价格和销售价格有详细的了解 两个类都有宽度:50%和内联块 我想写一个脚本,改变样式(添加类宽度100%和改变字体样式)的价格时,没有销售价格 这就是我到目前为止所尝试的 这是第一个代码:Javascript 当为空时隐藏div并将类添加到另一个div,javascript,jquery,Javascript,Jquery,我们对产品价格和销售价格有详细的了解 两个类都有宽度:50%和内联块 我想写一个脚本,改变样式(添加类宽度100%和改变字体样式)的价格时,没有销售价格 这就是我到目前为止所尝试的 这是第一个代码: jQuery(document).ready(function($) { if( $('.eg-top-ponudbe-content-element-28').html().trim().length === 0) { $('.eg-top-ponudbe-content-elemen
jQuery(document).ready(function($) {
if( $('.eg-top-ponudbe-content-element-28').html().trim().length === 0) {
$('.eg-top-ponudbe-content-element-28').hide();
$('.eg-top-ponudbe-content-element-24').addClass('change_regular_price');
}
});
这是第二个代码:
jQuery(document).ready(function($) {
if( $('.eg-top-ponudbe-content-element-28').is(':empty')) {
$('.eg-top-ponudbe-content-element-28').hide();
$('.eg-top-ponudbe-content-element-24').addClass('change_regular_price');
}
});
而且也不起作用,因为它隐藏了所有产品的销售价格(也包括具有销售价格的产品)
HTML是:
<div class="price_div">
<div class="esg-content eg-post-903 eg-top-ponudbe-content-element-28-a">
<a class="eg-top-ponudbe-content-element-28 eg-post-903" href="javascript:void(0);" target="_self">regular_price 1.200 €</a></div>
<div class="esg-content eg-post-903 eg-top-ponudbe-content-element-24-a">
<a class="eg-top-ponudbe-content-element-24 eg-post-903" href="javascript:void(0);" target="_self">sale_price 1.100 €</a></div>
</div>
</div>
您必须遍历每个价格分区,找到其中的常规和销售对,然后您可以独立于其他价格分区进行更新。行:
$(".price_div").each(function(_ix, el) {
var $priceDiv = $(el):
var $regularPrice = $priceDiv.find(".eg-top-ponudbe-content-element-28");
var $salePrice = $priceDiv.find(".eg-top-ponudbe-content-element-24");
if( $regularPrice.is(':empty')) {
$regularPrice.hide();
$salePrice.addClass('change_regular_price');
}
})
您可以使用jQuery选择带有$('.sale\u price:empty')的空sale\u price项,然后通过添加.each()循环结果
$('.sale\u price:empty')。每个(函数(){
$(this.hide();
$(this).parent().find('.regular_price').addClass('change_regular_price');
})
。销售价格{
宽度:50%;
背景:红色;
浮动:左;
}
.正常价格{
宽度:50%;
背景:蓝色;
浮动:左;
}
.常规价格。更改常规价格{
宽度:100%;
背景:绿色;
浮动:左;
}
保险商实验室{
列表样式:无;
}
-
$5.00
$7.00
-
$8.00
-
$15.00
$17.00
jQuery(文档).ready(函数($){
$(“.price_div”)。每个(函数(){
var regular_price=$(this.find('div:first child');
var sale_price=$(this.find('div:last child');
if(销售价格.查找('a').html().trim().length==0){
销售价格。隐藏();
常规价格。addClass(“更改常规价格”);
}
});
});代码>
.price\u div{
边缘底部:20px;
宽度:600px;
高度:40px;
边框:1px实心#ccc;
}
.价格部{
显示:内联块;
宽度:50%;
高度:40px;
线高:40px;
浮动:左;
文本对齐:居中;
}
.更改常规价格{
宽度:100%!重要;
}
听起来您需要使用DOM遍历来查找与.sale\u price
相关的.regular\u price
。我们可以向您展示如何做到这一点,但我们需要查看您的HTML。请编辑您的问题,使其包含在其中,这取决于您的销售价格的结构。如果价格包含在特定的HTML标记中,请使用find()然后检查值,如果该类中只有文本且没有任何标记,请使用text()并检查它,如果text=''发布一些JSFIDLE(或其他)至少谢谢,它可以工作,只有类别不会添加到常规价格中:/