$ .post()在函数内停止工作

时间:2014-09-16 17:44:11

标签: jquery

我正在使用jQuery ajax post函数在数据库中输入新行,然后在.done()上输出一些HTML

将它放入函数中效果很好。但出于某种原因,当我将它添加到一个函数时它停止工作。有谁能帮我解决这个问题?

以下是我的代码

功能页面:

function add_items(){



    var id = ($(this).attr("id"));

    //Insert a new row using an ajax post method, post the the id to reference
    //under which category the menu item should go under
    var adtnl_item = $.post("ItemCreate.php", {id : id })


    .fail(function(){
        console.log( "New Row Can't be added" );
    })

    //Append the new menu item input fields to the div class
    //.menu_item_wrapper that has an id of the mainØ category ID
    .done(function(data) {
         return $('.menu_item_wrapper[id="' + id + '"]').append(data);

    });

}

索引页:

    $(".add_item").on("click", function(){


        add_items();



    });

1 个答案:

答案 0 :(得分:0)

当您从on click函数内部调用add_items()时,this不再表示add_items函数内的元素。尝试将元素传递给函数

function page 

function add_items(el){
    var id = ($(el).attr("id"));

    //Insert a new row using an ajax post method, post the the id to reference
    //under which category the menu item should go under
    var adtnl_item = $.post("ItemCreate.php", {id : id })
    .fail(function(){
        console.log( "New Row Can't be added" );
    })

    //Append the new menu item input fields to the div class
    //.menu_item_wrapper that has an id of the mainØ category ID
    .done(function(data) {
         return $('.menu_item_wrapper[id="' + id + '"]').append(data);
    });
}

index page 

$(".add_item").on("click", function(){
    add_items(this);
});