代码之家  ›  专栏  ›  技术社区  ›  Bibek Shakya Dev. Joel

在jQuery中,使用e.preventDefault()不会将复选框状态显示为选中状态

  •  1
  • Bibek Shakya Dev. Joel  · 技术社区  · 6 年前

    我一直在尝试停止事件中的复选框点击表单提交。但无法在UI中显示选中状态。我还尝试使用本文中提到的单独的事件循环 answer

    首先,复选框将由ajax加载,并附加为HTML,以便我在事件中使用

    discountElement.rentalCompanyWithDiscountDiv
      .on('click', discountElement.rentalCompanyCheckBox, this.loadCamperFromCountryAndRentalCompany);
    

    下面是将checked属性添加到HTML并通过ajax调用另一个请求的代码

    loadTakeOverAndReturnableStation: function (e) {
            if (e.target.checked) {
                e.target.setAttribute('checked', 'checked');
                discountElement.camperIds.push(e.target.value);
            } else {
                e.target.removeAttribute('checked');
                discountElement.camperIds.splice(discountElement.camperIds.indexOf(e.target.value), 1);
            }
            if (discountElement.camperIds.length>0 && discountElement.rentalCompanyIds.length>0){
                var country_id = discountElement.country.val();
                var _token = discountElement._token.val();
                $.ajax({
                    url: discountElement.fetchStations.val(),
                    method: "POST",
                    headers: {
                        'X-CSRF-TOKEN': _token
                    },
                    data: {
                        country_id: country_id,
                        _method: 'POST',
                        'discount_id': discountElement.discountId.val(),
                        'rental_company_id': discountElement.rentalCompanyIds,
                        'camper_id': discountElement.camperIds
                    },
                    success: discountModule.fillDiv
                });
            }else{
                discountElement.takeOverStationsDiv.empty();
                discountElement.returnableStationsDiv.empty();
            }
    }
    

    e.preventDefault(); 它不会在UI中显示选中的状态,但工作时就像选中一样。

    当我尝试在setTimeout上实现checked state时,上面的答案是这样的

    e.preventDefault();
    setTimeout(function () {
    if (e.target.checked) {
        e.target.setAttribute('checked', 'checked');
        discountElement.camperIds.push(e.target.value);
    } else {
        e.target.removeAttribute('checked');
        discountElement.camperIds.splice(discountElement.camperIds.indexOf(e.target.value), 1);
    }
    },1);
    

    它不起作用,无论是在UI中显示签入还是在后台显示,

    0 回复  |  直到 6 年前