[英]How to combine two javascripts?
有没有人能告诉我如何修改这个JavaScript? 我承认我没有太多使用 JavaScript 的经验,我已经尝试过自己,但最终有点迷失。
解释一下,WooCommerce 在我的网站上以 .columns-3 和 .columns-4 输出产品,并相应地分配 .first 和 .last 类。
如果网站是在移动设备上加载的,下面的脚本将删除 .first 和 .last 标签,并重新分配它们以在两列中显示产品。
该脚本目前仅针对function defaultProductRows
和function adjustProductRows
.columns-3 。 我还需要在同一个脚本中定位 .columns 4,但我不确定如何添加它。
<script>
$(window).on('load resize', function (){
var windowWidth = $(window).width();
if(windowWidth < 753){ // this is my screen size break point for the rows
adjustProductRows(); // call the function to adjust add last and first classes
} else {
defaultProductRows(); // else if large screen size then get everything back to defalut
}
});
function defaultProductRows(){
var products = $('ul.products.columns-3 li.type-product');
products.each(function(idx, li) {
var product = $(li);
// remove all classes we added
$('ul.products li.adjusted-row.first').removeClass('adjusted-row first');
$('ul.products li.adjusted-row.last').removeClass('adjusted-row last');
if(idx == 0) { // make sure first li tag gets first class
product.addClass('first');
}
else if((idx+1) % 3 == 0) //this will make sure we have 3 rows by adding last classes after each 3 products
{
product.addClass('last');
}
else if(idx % 3 == 0)
{
product.addClass('first'); // make sure all products divided by 3 will have first class
}
else
{
console.log(idx); // just checking for the index
}
});
}
function adjustProductRows() {
var products = $('ul.products.columns-3 li.type-product');
products.each(function(idx, li) {
var product = $(li);
if(idx % 2 == 0) // we are even
{
product.addClass('adjusted-row first');
product.removeClass('last');
}
else // we are odd
{
product.addClass('adjusted-row last');
product.removeClass('first');
}
});
}</script>
更改您的选择器以包含第 4 列
从:
var products = $('ul.products.columns-3 li.type-product');
到:
var products = $('ul.products.columns-3 li.type-product, ul.products.columns-4 li.type-product');
这告诉 jQuery 选择属于 columns-3 或 columns-4 的 li.type-products
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.