单击中每个循环的事件多次激发



我有一个.each循环,如下所示:

$('.form-base-subscriptions input').each(function (index, value) {
    var uniqueId = $(this).attr('id'),
        uniqueId = uniqueId.substring(uniqueId.lastIndexOf('_')),
        $parent = $(this).parent(),
        $content = $parent.html();
        $content = $content.split('~'),
        input = $content[0],
        amount = $content[4],
var $toggle = $parent.find('.form-toggle'),
    $checkbox = $toggle.find('input');
    $toggle.on('click', function () {
        $('.form-base-subscriptions .form-toggle').removeClass('active');
        $('.form-base-subscriptions input').prop('checked', false);
        $toggle.addClass('active');
        $checkbox.prop('checked', true);
            var currentId = $(this).attr("id");
            if (currentId == "toggle_151" || currentId == "toggle_170") {
                amount = '1.50';
            } else {
                console.log('check');
                amount = '0';
            }
            $('#toggle_153 input').attr('data-amount', amount);
            $('#toggle_153 span').html(amount);
        //updateWellnessPrice();
        updateSubscriptionAmount();
    });

如何每次单击仅触发一次此onCLick event?现在,每次单击都会触发两次。

循环后初始化事件

var $toggle = '';
  $('.form-base-subscriptions input').each(function (index, value) {
    var uniqueId = $(this).attr('id'),
        uniqueId = uniqueId.substring(uniqueId.lastIndexOf('_')),
        $parent = $(this).parent(),
        $content = $parent.html();
        $content = $content.split('~'),
        input = $content[0],
        amount = $content[4],
   $toggle = $parent.find('.form-toggle'),
    $checkbox = $toggle.find('input');
});
$toggle.on('click', function () {
            $('.form-base-subscriptions .form-toggle').removeClass('active');
            $('.form-base-subscriptions input').prop('checked', false);
            $toggle.addClass('active');
            $checkbox.prop('checked', true);
            updateWellnessPrice();
            updateSubscriptionAmount();
        });

将一个类放在所有相关元素中,并为此类添加一个事件侦听器:

HTML

<div id="toggle_n" class="myElem"> .. </div>
...

jQuery

$(document).on('click', '.myElem', function() {
   // Do your stuff here ..
});

最新更新