addClass() based on the presence of another class?
addClass() based on the presence of another class?
我正在开发一个电子商务商店的产品页面,需要显示一个"库存"图形和一个"缺货"图形。该平台有一些局限性,但有一个显示缺货图片但不显示库存图片的设置。
我想做的是默认情况下将库存图形硬编码到页面中。像这样:
<div class="inStock"></div>
下面的CSS:
.inStock {
width: 143px;
height: 40px;
background: url('../product_images/uploaded_images/in-stock.jpg');
margin-left: 60%;
margin-top: 5%;
position: absolute;
}
当产品缺货时,平台后端会自动在页面中添加一个如下所示的div:
<div class="CurrentlySoldOut">
<p>
<span lang="en">Sorry but this item is currently unavailable.</span>
</p>
</div>
当类"CurrentlySoldOut"出现时,它是从平台自动生成的,我想通过后台atrribute用缺货来覆盖当前硬编码的"库存"图形。类似这样的东西:
background: url('../product_images/uploaded_images/out-of-stock.jpg');.
简而言之,有没有一种方法可以根据另一个类的存在来覆盖CSS类。有点像"如果"CurrentlySoldOut类正在显示,那么将class添加到另一个div"(我将在其中控制图形。)
如果您只需要在页面初始加载时发生这种情况,那么只要存在任何具有匹配选择器.CurrentlySoldOut
的元素,就可以更改类:
if ($('.CurrentlySoldOut').length > 0) {
$('.inStock').removeClass('inStock').addClass('outOfStock');
}
当然,您需要将outOfStock
类的样式/图像url添加到css中。
如果您的页面正在更新,而用户已经在查看它,那么它将稍微更多地参与其中。您可以监听对DOM的更改,然后调用上面的代码。类似的东西在Chrome和Firefox中有效:
function updateInStockStatus() {
// same code as above
if ($('.CurrentlySoldOut').length > 0) {
$('.inStock').removeClass('inStock').addClass('outOfStock');
}
}
// listen for DOM updates, calling above function
$('body').bind('DOMSubtreeModified', function() {
updateInStockStatus();
});
由于您可能想要支持IE;)您可以使用具有上述功能的setInterval
定期检查状态是否已更改:
window.setInterval(updateInStockStatus, 5000);
这将每5秒检查一次,因为延迟以毫秒为单位。
试试这个:
if($('.CurrentlySoldOut').length)//true when CurrentlySoldOut exists
$('.inStock').css("background", "url(../product_images/uploaded_images/out-of-stock.jpg");; //change bg image
您可以添加一个具有新背景的类,因为类名似乎已经更新:
.inStock {
width: 143px;
height: 40px;
background: url('../product_images/uploaded_images/in-stock.jpg');
margin-left: 60%;
margin-top: 5%;
position: absolute;
}
.CurrentlySoldOut{
width: 143px;
height: 40px;
background: url('../product_images/uploaded_images/in-stock.jpg');
margin-left: 60%;
margin-top: 5%;
position: absolute;
}
试试这个
if ($(".CurrentlySoldOut")[0])
$('.inStock').css("background", "url(../product_images/uploaded_images/out-of-stock.jpg");
相关文章:
- HighChart : Usage of setData
- Difference between methods of defining JavaScript 'class
- 为什么我在下面的..of循环中得到意外令牌
- Appending the innerhtml of <th>
- Animation cuts off multiple lines of text in <p>
- Trouble overlaying one div with another with JavaScript &
- javascript: functionname() instread of functionname()
- jQuery使用.of()删除事件处理程序时出现的问题
- Three.js issue creating meshes outside of loader's load(
- jquery in the middle of html
- JavaScript equivalent of C#'s DynamicObject?
- nodejs console.log of object
- value of jquery sortable
- Javascript imageData returns array of 0's
- 对于grunt构建中的(let.of)错误
- Opposite of jQuery's :eq()
- Implementation of jQuery 'animate' with Meteor
- 当调用.of()然后调用.on()时,Jquery是否可能将事件推迟
- Angularjs ng-options selected value of dropdownlist
- addClass() based on the presence of another class?