jQuery Remove attribute in ajax

jQuery Remove attribute in ajax

本文关键字:ajax in attribute Remove jQuery      更新时间:2023-09-26

我有一个 ajax 调用,我禁用了一个复选框,然后我想在 ajax 完成后再次启用。但是,我无法删除禁用的属性。

$(function(){ // added
    $("input:checkbox").live("click", function(){
        var a_href = $(this).attr('id');
        var checked = $(this).attr('checked');
        if (checked == 'checked') {
            checked = 1;
        }else {
            checked = 0
        };
        $(this).parent().parent().after('<img class="loader" style="padding-botton:0 !important;" alt="" src="images/loaders/loader.gif">');
        $(this).attr('disabled','disabled');
        $.ajax( {
            type: "POST",
            url: "includes/featured.php",
            data: { id: a_href, value: checked, field: "main_feature" },
          success: function(data) {
            $('img.loader').fadeOut('slow',function(){$(this).remove()});
            $(this).removeAttr('disabled'); 
          }             
        }).done(function (data){
            }
        );
    return false; 

    });
}); // added

我也尝试过:

.attr('disabled', false);

您需要保存对this的引用,因为 ajax 回调this是 ajax 请求。

$("input:checkbox").live("click", function(){
    var $this = $(this);
    ...
    ...
    success: function(data) {
        $('img.loader').fadeOut('slow',function(){$(this).remove()});
        $this.removeAttr('disabled');

或将context设置为 this

    $.ajax( {
        type: "POST",
        context: this, // <===============
        url: "includes/featured.php",
        data: { id: a_href, value: checked, field: "main_feature" },
      success: function(data) {
          // Now this is the checkbox!
        $('img.loader').fadeOut('slow',function(){$(this).remove()});
        $(this).removeAttr('disabled'); 
      }  

AJAX 成功处理程序中的this将不是复选框。您需要先缓存该变量,然后才能在成功处理程序中使用它。还值得注意的是,删除属性时最好使用 propremoveProp。试试这个:

$(function(){ // added
    $("input:checkbox").live("click", function(){
        var $checkbox = $(this);
        var a_href = $checkbox.attr('id');
        var checked = $checkbox.attr('checked');
        checked = (checked == "checked") ? 1 : 0;
        $checkbox.parent().parent().after('<img class="loader" style="padding-botton:0 !important;" alt="" src="images/loaders/loader.gif">');
        $checkbox.attr('disabled','disabled');
        $.ajax( {
            type: "POST",
            url: "includes/featured.php",
            data: { id: a_href, value: checked, field: "main_feature" },
            success: function(data) {
                $('img.loader').fadeOut('slow',function(){$(this).remove()});
                $checkbox.removeProp('disabled'); 
            }             
        }).done(function (data) {});
        return false;
    });
});
我不

认为成功函数中的"这个"是你认为的那样。尝试在复选框的 ajax 作用域之外设置一个变量,然后在成功函数中引用该变量。

当您

尝试重新启用复选框时,您的$(this)超出了范围。

在之后添加var newthis = $(this)

$("input:checkbox").live("click", function(){

并将您的来电以移除"已禁用"属性更改为

newthis.removeAttr('disabled');