is this the full code for javascript partt in my cart.php? becase the javascript part is not functioning
<script>
jQuery(function($) {
// =============================================
// 核心功能函数
// =============================================
// 实用工具:全选辅助函数
function getHeaderSA() {
return $('#select-all-items, #select-all-items-header').length ?
$('#select-all-items, #select-all-items-header') :
$('table.shop_table thead th.product-select input[type="checkbox"]').first();
}
function getFooterSA() {
return $('#footer-select-all, #select-all-items-footer').length ?
$('#footer-select-all, #select-all-items-footer') :
$('.cart-footer-actions input[type="checkbox"]').first();
}
function $items() {
return $('.woocommerce-cart-form .item-checkbox');
}
// AJAX 助手函数
function getAjaxUrl() {
return (window.wc_cart_params && window.wc_cart_params.ajax_url) ||
'<?php echo esc_url(admin_url("admin-ajax.php")); ?>';
}
function getCartNonce() {
const n = $('input[name="woocommerce-cart-nonce"]').val();
return n || '<?php echo wp_create_nonce("woocommerce-cart"); ?>';
}
function fmtRM(n) {
return 'RM' + (isNaN(n) ? 0 : n).toFixed(2);
}
// =============================================
// 收藏列表管理(兼容 Woodmart 主题)
// =============================================
// 获取收藏列表
function getScWishlist() {
try {
// 优先使用 Woodmart 主题的收藏列表
if (typeof window.woodmart !== 'undefined' && window.woodmart.wishlist) {
const woodmartList = window.woodmart.wishlist.getWishlist();
return woodmartList.map(item => ({
productId: item.product_id,
variationId: item.variation_id || 0
}));
}
// 使用本地存储作为备用
const wishlistJson = localStorage.getItem('sc_wishlist');
return wishlistJson ? JSON.parse(wishlistJson) : [];
} catch (error) {
console.error('获取收藏列表出错:', error);
return [];
}
}
// 保存收藏列表
function saveScWishlist(wishlist) {
try {
// 优先同步到 Woodmart 主题
if (typeof window.woodmart !== 'undefined' && window.woodmart.wishlist) {
// 清空现有收藏
window.woodmart.wishlist.clearCache();
// 重新添加所有项目
wishlist.forEach(item => {
window.woodmart.wishlist.add(item.productId, item.variationId);
});
}
// 保存到本地存储
localStorage.setItem('sc_wishlist', JSON.stringify(wishlist));
return true;
} catch (error) {
console.error('保存收藏列表出错:', error);
return false;
}
}
// 检查商品是否在收藏列表中
function isInScWishlist(productId, variationId = 0) {
try {
const wishlist = getScWishlist();
return wishlist.some(item =>
parseInt(item.productId) === parseInt(productId) &&
parseInt(item.variationId || 0) === parseInt(variationId || 0)
);
} catch (error) {
console.error('检查收藏状态出错:', error);
return false;
}
}
// 添加到收藏列表
function addToScWishlist(productId, variationId = 0) {
try {
const wishlist = getScWishlist();
// 检查是否已存在
const exists = wishlist.some(item =>
parseInt(item.productId) === parseInt(productId) &&
parseInt(item.variationId || 0) === parseInt(variationId || 0)
);
if (!exists) {
wishlist.push({
productId: parseInt(productId),
variationId: variationId ? parseInt(variationId) : 0
});
return saveScWishlist(wishlist);
}
return false; // 已存在
} catch (error) {
console.error('添加收藏出错:', error);
return false;
}
}
// 从收藏列表移除
function removeFromScWishlist(productId, variationId = 0) {
try {
const wishlist = getScWishlist();
const initialLength = wishlist.length;
const filtered = wishlist.filter(item =>
!(parseInt(item.productId) === parseInt(productId) &&
parseInt(item.variationId || 0) === parseInt(variationId || 0))
);
if (filtered.length !== initialLength) {
return saveScWishlist(filtered);
}
return false; // 未找到
} catch (error) {
console.error('移除收藏出错:', error);
return false;
}
}
// =============================================
// 收藏按钮状态管理
// =============================================
// 更新所有收藏按钮状态
function updateWishlistButtons() {
$('.wishlist-btn').each(function() {
const $btn = $(this);
const productId = $btn.data('product-id');
const variationId = $btn.data('variation-id') || 0;
const inWishlist = isInScWishlist(productId, variationId);
$btn.toggleClass('added', inWishlist);
$btn.attr('title', inWishlist ? '浏览收藏列表' : '加入收藏');
$btn.data('in-wishlist', inWishlist.toString());
// 控制台日志用于调试
console.log(`产品 ${productId} (变体 ${variationId}) 收藏状态: ${inWishlist}`);
});
}
// 收藏状态同步机制
function setupWishlistSync() {
// 监听本地存储变化(跨标签页同步)
$(window).on('storage', function(e) {
if (e.originalEvent.key === 'sc_wishlist') {
console.log('检测到收藏列表变化,更新按钮状态...');
updateWishlistButtons();
}
});
// 自定义事件监听(同一页面内同步)
$(document).on('wishlistUpdated', function() {
console.log('收到自定义收藏更新事件');
updateWishlistButtons();
});
// 每5秒检查一次状态(防止意外不同步)
setInterval(updateWishlistButtons, 5000);
}
// 处理收藏按钮点击
function handleWishlistButtonClick(e) {
e.preventDefault();
const $btn = $(this);
const productId = $btn.data('product-id');
const variationId = $btn.data('variation-id') || 0;
const inWishlist = $btn.data('in-wishlist') === 'true';
console.log('收藏按钮点击', { productId, variationId, inWishlist });
if (inWishlist) {
// 已在收藏列表中 - 跳转到收藏页面
console.log('跳转到收藏列表页面');
window.location.href = "<?php echo home_url('/wishlist'); ?>";
} else {
// 添加到收藏列表
if (addToScWishlist(productId, variationId)) {
console.log('成功添加到收藏列表');
showWishlistMessage('商品已添加到收藏列表', 'success');
// 更新按钮状态
updateWishlistButtons();
// 触发同步事件
$(document).trigger('wishlistUpdated');
window.dispatchEvent(new Event('storage'));
} else {
console.log('添加失败或已在收藏列表中');
showWishlistMessage('商品已在收藏列表中', 'info');
}
}
}
// 显示收藏操作消息
function showWishlistMessage(message, type = 'success') {
$('.wishlist-message').remove();
const bgColor = type === 'success' ? '#4CAF50' :
type === 'error' ? '#f44336' : '#2196F3';
const $message = $(`
<div class="wishlist-message ${type}" style="background: ${bgColor}">
${message}
</div>
`);
$('body').append($message);
setTimeout(() => {
$message.fadeOut(300, function() {
$(this).remove();
});
}, 3000);
}
// =============================================
// 购物车核心功能
// =============================================
// 更新选中商品摘要
function updateSelectedSummary() {
let count = 0, total = 0;
$('.item-checkbox:checked').each(function() {
const quantity = parseFloat($(this).data('quantity')) || 1;
const price = parseFloat($(this).data('price')) || 0;
count += quantity;
total += price;
});
$('#selected-count').text(count);
$('#selected-total').text(fmtRM(total));
}
// 全选逻辑
function refreshSelectAllFromItems() {
const $all = $items();
const total = $all.length;
const checked = $all.filter(':checked').length;
const allChecked = total > 0 && checked === total;
getHeaderSA().prop('checked', allChecked);
getFooterSA().prop('checked', allChecked);
}
// 修复删除按钮显示
function fixRemoveButtonDisplay() {
$('<style>.product-remove .remove::before { content: "" !important; }</style>').appendTo('head');
$('.product-remove .remove').each(function() {
const $btn = $(this);
if ($btn.html().trim() === '') {
$btn.html('X');
}
});
}
// 获取商品库存信息
function getProductStockInfo(productId, variationId = 0) {
return new Promise((resolve) => {
$.post(getAjaxUrl(), {
action: 'get_product_stock_info',
security: getCartNonce(),
product_id: productId,
variation_id: variationId
}, function(response) {
response && response.success ? resolve(response.data) : resolve({});
}).fail(() => resolve({}));
});
}
// 初始化库存数据
async function initializeStockData() {
const promises = [];
$('.item-checkbox').each(function() {
const $checkbox = $(this);
const $row = $checkbox.closest('tr');
const $input = $row.find('.qty');
const productId = $checkbox.data('product-id');
const variationId = $checkbox.data('variation-id') || 0;
if (productId) {
const promise = getProductStockInfo(productId, variationId).then(stockInfo => {
const maxStock = stockInfo.stock_quantity || stockInfo.max_purchase_quantity || 0;
if (maxStock > 0) {
$input.attr({
'max': maxStock,
'data-stock': maxStock
});
const currentQty = parseInt($input.val()) || 1;
if (currentQty > maxStock) {
$input.val(maxStock);
$checkbox.data('quantity', maxStock).attr('data-quantity', maxStock);
setTimeout(() => saveQuantityAjax($input, true), 500);
}
}
});
promises.push(promise);
}
});
await Promise.all(promises);
}
// 处理库存超限
function handleOverstock($input, immediateSave = false) {
const maxStock = parseInt($input.attr('data-stock')) || parseInt($input.attr('max')) || 0;
const currentQty = parseInt($input.val()) || 0;
if (maxStock > 0 && currentQty > maxStock) {
alert(`此商品库存仅剩 ${maxStock}`);
$input.val(maxStock);
if (immediateSave) saveQuantityAjax($input, false);
return true;
}
return false;
}
// 保存数量变更
function saveQuantityAjax($input, showNotice = true) {
if (!$input.length) return;
const $row = $input.closest('tr');
const cart_item_key = $row.find('.item-checkbox').val();
let newQty = parseFloat($input.val()) || 1;
if (handleOverstock($input, false)) {
newQty = parseFloat($input.val()) || 1;
}
$input.prop('disabled', true);
$row.find('.plus, .minus').prop('disabled', true);
$.post(getAjaxUrl(), {
action: 'update_cart_item_qty',
security: getCartNonce(),
cart_item_key,
qty: newQty
}, function(response) {
if (response?.success) {
const d = response.data || {};
const $checkbox = $row.find('.item-checkbox');
if (d.subtotal_html) $row.find('.product-subtotal').html(d.subtotal_html);
if (d.discounted_price) $checkbox.data('price', d.discounted_price).attr('data-price', d.discounted_price);
if (d.unit_price) $checkbox.data('unit-price', d.unit_price).attr('data-unit-price', d.unit_price);
if (d.adjusted_qty) $input.val(d.adjusted_qty).attr('data-quantity', d.adjusted_qty);
if (d.max_stock) $input.attr('max', d.max_stock).attr('data-stock', d.max_stock);
if (showNotice && d.notice) alert(d.notice);
if (d.unit_price !== undefined) $row.find('td.product-price').html(fmtRM(d.unit_price));
updateSelectedSummary();
setTimeout(refreshSelectAllFromItems, 0);
}
}).always(function() {
$input.prop('disabled', false);
$row.find('.plus, .minus').prop('disabled', false);
});
}
// =============================================
// 事件绑定
// =============================================
function bindEvents() {
// 商品选择变更
$(document).on('change', '.woocommerce-cart-form .item-checkbox', function() {
updateSelectedSummary();
setTimeout(refreshSelectAllFromItems, 0);
});
// 顶部全选
$(document).on('change', '#select-all-items, #select-all-items-header, table.shop_table thead th.product-select input[type="checkbox"]', function() {
const checked = $(this).prop('checked');
$items().prop('checked', checked).trigger('change');
});
// 底部全选
$(document).on('change', '#footer-select-all, #select-all-items-footer, .cart-footer-actions input[type="checkbox"]', function() {
const checked = $(this).prop('checked');
const $header = getHeaderSA();
$header.length ? $header.prop('checked', checked).trigger('change') : $items().prop('checked', checked).trigger('change');
});
// 数量输入事件
$('.woocommerce-cart-form').on({
'input change': function() { handleOverstock($(this), false); },
'blur': function() { !handleOverstock($(this), false) && saveQuantityAjax($(this), true); },
'keydown': function(e) {
if (e.key === 'Enter') {
e.preventDefault();
!handleOverstock($(this), false) && saveQuantityAjax($(this), true);
}
}
}, '.qty');
// 数量按钮
$('body').on('click', '.plus, .minus', function(e) {
e.stopImmediatePropagation();
const $input = $(this).closest('.quantity').find('input.qty');
const currentQty = parseInt($input.val()) || 0;
const newQty = Math.max(1, currentQty + ($(this).hasClass('plus') ? 1 : -1));
$input.val(newQty);
if (!handleOverstock($input, false)) {
clearTimeout($input.data('buttonSaveTimer'));
$input.data('buttonSaveTimer', setTimeout(() => saveQuantityAjax($input, true), 300));
}
});
// 删除选中商品
$('#remove-selected-items').on('click', function() {
const keys = $('.item-checkbox:checked').map(function(){ return $(this).val(); }).get();
if (!keys.length) return alert('请先选择要删除的商品');
$.post(getAjaxUrl(), {
action: 'remove_selected_cart_items',
security: getCartNonce(),
cart_item_keys: keys
}, function(response) {
if (response?.success) {
keys.forEach(k => $(`.item-checkbox[value="${k}"]`).closest('tr').remove());
updateSelectedSummary();
setTimeout(refreshSelectAllFromItems, 0);
}
});
});
// 清空购物车
$('#clear-cart').on('click', function() {
if (!confirm('确定要清空整个购物车吗?')) return;
$.post(getAjaxUrl(), { action: 'empty_cart', security: getCartNonce() }, function(response) {
if (response?.success) {
$('.woocommerce-cart-form__cart-item').remove();
updateSelectedSummary();
setTimeout(refreshSelectAllFromItems, 0);
}
});
});
// 应用优惠券
$('#apply-coupon').on('click', function() {
const code = $('#coupon_code').val().trim();
if (!code) return alert('请输入优惠券代码');
$.post(getAjaxUrl(), {
action: 'apply_coupon',
security: getCartNonce(),
coupon_code: code
}, function(response) {
if (response?.success) {
alert('优惠券应用成功!');
setTimeout(() => location.reload(), 300); // 刷新页面更新优惠信息
} else {
alert((response.data && response.data.message) || '优惠券应用失败');
}
}).fail(() => alert('网络错误,请重试'));
});
// 部分结算
$('#partial-checkout').on('click', function(e) {
e.preventDefault();
const keys = $('.item-checkbox:checked').map(function(){
return $(this).val();
}).get();
if (keys.length === 0) {
alert('请至少选择一件商品结算');
return false;
}
// 保存选中的商品到 sessionStorage
sessionStorage.setItem('selected_cart_items', JSON.stringify(keys));
// 延迟跳转确保 sessionStorage 已设置
setTimeout(() => {
window.location.href = $('#partial-checkout').attr('href');
}, 100);
});
// 绑定收藏按钮事件
$(document).on('click', '.wishlist-btn', handleWishlistButtonClick);
// =============================================
// 初始化函数
// =============================================
// 购物车初始化
async function initializeCart() {
// 1. 修复删除按钮显示问题
fixRemoveButtonDisplay();
// 2. 初始化库存数据
await initializeStockData();
// 3. 更新选中商品摘要
updateSelectedSummary();
// 4. 刷新全选状态
refreshSelectAllFromItems();
// 5. 初始化收藏按钮状态
updateWishlistButtons();
// 6. 设置收藏状态同步
setupWishlistSync();
// 7. 绑定所有事件
bindEvents();
console.log('购物车初始化完成');
}
// 页面加载时初始化
$(document).ready(function() {
initializeCart();
// WooCommerce 片段更新后重新初始化
$(document.body).on('updated_wc_div', function() {
setTimeout(initializeCart, 300);
});
});
});
</script>