You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery无法获取Elementor添加元素的值,求解决方案

解决方法

问题根源

你用了.val()方法,但这个方法只适用于表单输入类元素(如input、select、textarea),而你的产品价格和运费元素都是div/a这类普通元素,所以无法读取值。另外你的点击事件选择器#ship-price也和实际HTML里的#ship-price-a/#ship-price-b不匹配。

修正后的代码

<script>
jQuery(document).ready(function($){
    // 给两个运费链接绑定点击事件
    $('#ship-price-a, #ship-price-b').on('click', function(e){
        e.preventDefault(); // 阻止a标签默认跳转行为
        
        // 1. 获取产品价格(提取数值)
        var priceText = $('#product-price .woocommerce-Price-amount').text().trim();
        // 去掉非数字和逗号,替换为点以便转换为浮点数
        var originalPrice = parseFloat(priceText.replace(/[^\d,]/g, '').replace(',', '.'));
        console.log('产品价格:', originalPrice);
        
        // 2. 获取当前点击的运费(提取数值)
        var shipText = $(this).text().trim();
        var shipPrice = parseFloat(shipText.replace(/[^\d]/g, ''));
        console.log('运费:', shipPrice);
        
        // 3. 计算总价并展示(示例逻辑,可按需修改)
        var totalPrice = originalPrice + shipPrice;
        // 还原为带逗号和欧元符号的格式
        var formattedTotal = totalPrice.toFixed(2).replace('.', ',') + ' €';
        console.log('总价:', formattedTotal);
        // 示例:将总价插入到页面元素,需提前准备id为total-price的元素
        // $('#total-price').text('总价: ' + formattedTotal);
    });
});
</script>

代码说明

  • 选择器修正:绑定点击事件到实际存在的#ship-price-a和#ship-price-b,同时阻止a标签默认跳转行为。
  • 文本提取与数值转换:用.text()获取普通元素的文本内容,通过正则过滤非数值部分,转换为浮点型方便计算。
  • 格式兼容:针对你提供的价格格式(逗号作为小数点分隔符),做了格式转换处理,确保计算和展示的一致性。

额外注意

如果产品价格是动态加载的(比如WooCommerce切换产品变体时更新价格),需要改用事件委托模式绑定点击事件,避免动态元素无法触发:

$(document).on('click', '#ship-price-a, #ship-price-b', function(e){
    // 内部逻辑和上面一致
});

内容的提问来源于stack exchange,提问作者OHICT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:42:41