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

时间:2019-02-12 05:05:34

标签: javascript jquery

我一直试图在单击复选框时停止提交表单。但是无法在用户界面中显示选中状态。我也曾尝试使用answer中提到的单独的事件循环。

首先,该复选框将由ajax加载,并作为HTML附加,因此我一直在使用事件

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

这里是用于将选中的属性添加到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();时,它不会在用户界面中显示选中状态,但是就像被选中一样工作。

当我尝试像上述答案一样在setTimeout上实现检查状态时

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);

它不起作用,无论是在用户界面中还是在背景中显示为选中状态,

0 个答案:

没有答案