需要帮助来定位/修改自定义数据属性

Need help to target / modify custom data attribute

本文关键字:修改 自定义 数据属性 定位 帮助      更新时间:2023-09-26

我正在使用Woocommerce在WordPress中的网站/网上商店工作,并尝试在"添加到购物车"按钮旁边添加一个数量字段。

我找到了这篇文章/教程:如何在WooCommerce中向产品存档添加数量(并保留ajax) - Christian Vargahttp://christianvarga.com/how-to-add-quantity-to-product-archives-in-woocommerce-and-keep-ajax/

它有两个小片段 - 第一个片段在我的函数.php文件中复制/粘贴后将正常工作。第二个是一些javascript代码,它将使数量字段与"添加到购物车"按钮一起工作。

这是代码:

$('.input-text.qty', 'ul.products').on('change', function() {
    $(this).closest('div').next('a').attr('data-quantity', $(this).val());
});

当我插入javascript代码时,没有任何反应。这是因为我使用自定义主题(Avada),我猜它具有不同的结构。

这也写在教程中:

*注意:这适用于WooCommerce的默认HTML结构,但是如果您使用的是自定义主题,则HTML结构可能会有所不同,因此 您需要修改此脚本以适合。

这是我页面的链接:http://frisk-matic.identitest.dk/kaffe/

我试图定位我的"添加到购物车"按钮,但我无法让它工作,而且我在 Javascript 方面不是那么熟练。有人可以帮助我吗?如果我能稍微了解一下这段代码是如何工作的,我会很高兴。

我知道第一行是选择我们添加的数量字段和产品div,结果是更改按钮的数据数量属性。

此致敬意萨姆兹3n

像这样试试

$('.input-text.qty').on('change', function() {
    $(this).parent().next('a.add_to_cart_button').attr('data-quantity', $(this).val());
});

问题是您的 html 标记与此模板不同。我已经检查了标记并编写了一些jQuery代码。我想它会为你做这件事!:)

$('.quantity').find('input[type="number"]').on('change',function(){
    $(this).parent().next('.product-buttons').find('.add_to_cart_button').data('quantity',$(this).val());
});

你可能和你的jQuery库有一些名称冲突,你可以试试这个

var $ = jQuery;
$('.quantity').find('input[type="number"]').on('change', function () {
  var value = $(this).val();
  var button = $(this).parent().next('.product-buttons').find('.add_to_cart_button');
  button.attr('data-quantity', value);
});

或者更好的是,使用它,直到你修复与jQuery的命名冲突

jQuery('.quantity').find('input[type="number"]').on('change', function () {
  var value = jQuery(this).val();
  var button = jQuery(this).parent().next('.product-buttons').find('.add_to_cart_button');
  button.attr('data-quantity', value);
});