覆盖从val()检索到的变量



在下面的代码中,当有人启动单击函数时,我将如何重写"donateAmount"变量?

换句话说,每当有人点击时,它就会删除变量"donateAmount"中的内容,并用新的val() amount代替。

谢谢

由于修复了变量作用域的问题,下面的代码现在可以工作了。

$('label input').click(function () {
    if ($('label input').is(':checked')) {
        $(this).parent().addClass('checked');
        $('.donate-now label').not($(this).parent()).removeClass('checked');
        var donateAmount = $(".checked input").val();

     }

    $('#click').click(function(){
        if ($('label #other').is(':checked')) {
            donateAmount = $("#otherAmount").val();
        }
           $('p').html(donateAmount);
    });   
 });

试试这个

 var donateAmount = $(".checked input").val();
$('label input').click(function () {
    var $this = $(this);
    if ($this.is(':checked')) {
        $this.closest('label').addClass('checked');
        $('.donate-now label').not($this.closest('label')).removeClass('checked');
        donateAmount = $this.val();
        if ($('#other').is(':checked')) {
           donateAmount = $("#otherAmount").val();
        }
    }
});
$('#otherAmount').change(function() {
    donateAmount = this.value;
});
$('#click').click(function () {
    $('p').html('$' + donateAmount);
});

检查小提琴

您定义单击事件的方式$('#click').click(function ()将多次绑定事件,每次单击一次。

所以把事件移到click事件之外

还可以尝试使用.on来绑定事件处理程序。

.click(function () {变为.on('click', function () {

最新更新