1

当我选择"Keyboard layout"它使用 js 生成按钮时 - 但点击事件不适用于动态生成的按钮。我认为,这是因为当文档准备好时,元素“ .prices-tier”不存在。它仅在我选择布局时生成。

在此处输入图像描述

我的部分代码:

    require(['jquery'], function(){
    jQuery(document).ready(function(){
        const currencySymbol = jQuery('.price').text()[0];
        var standartPrice = Number(jQuery('.price-wrapper').attr('data-price-amount'));



        jQuery('.prices-tier').on('click','.btn', function () {
            var quantity = Number(jQuery(this).attr("data-qty"));
            var price = jQuery(this).attr("data-amount");
            jQuery('.qty-default').val(quantity);
            jQuery('#product-price-'+"<?php echo $_product->getId();?>"+' .price').html(currencySymbol+price);
            // jQuery('.product-info-main>div>.price-box>.price-container>.price-wrapper>.price').html(currencySymbol+price);
            jQuery('.qty-default').trigger('input');
        }
        );

生成的html元素:

<div class="prices-tier items w-75 btn-group">

        <button type="button" class="btn btn-light border border-bottom-0 border-top-0 bg-primary" data-qty="25" data-amount="27.21" onclick="">

        4%</button>

        <button type="button" class="btn btn-light border border-bottom-0 border-top-0 bg-primary" data-qty="50" data-amount="26.5" onclick="">

        6%</button>
</div>
4

1 回答 1

2

您需要使用事件委托并将您的侦听器附加到父级(已存在于 DOM 中)或document. 这样,事件就可以从新元素中冒出来并被侦听器捕获。

jQuery(document).on('click', '.prices-tier .btn', function () {

注意,这不仅仅是一个 jQuery 技巧,这就是 JS 事件的工作方式。例如,它在您拥有项目列表 (1000) 但不想为每个项目添加事件侦听器的情况下也很有用。您将一个事件侦听器附加到父容器(<ul>可能是一个),它可以捕获从其子容器冒出的所有事件并处理它们。

于 2019-05-19T17:33:48.813 回答