选择上一个“this”元素

时间:2013-05-02 11:40:25

标签: javascript jquery

我有一段javascript代码,我试图获取前面声明的元素。目前,我有两个onclick功能。

$('#formIngredient').on("click", '.newIngredient', function() {
    value = $(this).attr('data-name');
    $(this).attr('data-isactive', 'true');

    $('#newIngredientInput').val(value);
    $('#newIngredient').modal('show')

    $('#createNewIngredient').click(function() {
        inputName = $('#newIngredientInput').val();
        inputCategory = $('#newIngredientCategory').val();

        var newIngredient = $.ajax({
            type: "GET",
            url: '/content/includes/ajax/createNewIngredient.php',
            data: {name: inputName, id_category: inputCategory}
        });

        newIngredient.done(function(result) {
            //PAI.showPage(PAI['PAGE']);
            $(this).parent().replaceWith('Hello');
            $('#newIngredient').modal('hide');
        });
    });
});

我正在尝试使用此代码的前一个元素。

$(this).parent().replaceWith('Hello');

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

$(this)的范围似乎是您的问题......您需要更正代码。

$('#createNewIngredient').click(function() {
    var self = this; // This is the #createNewIngredient element

    inputName = $('#newIngredientInput').val();
    inputCategory = $('#newIngredientCategory').val();

    var newIngredient = $.ajax({
        type: "GET",
        url: '/content/includes/ajax/createNewIngredient.php',
        data: {name: inputName, id_category: inputCategory}
    });

    newIngredient.done(function(result) {
        //PAI.showPage(PAI['PAGE']);
        // $(this).parent().replaceWith('Hello'); // $(this) scope is lost to current function... so
        $(self).parent().replaceWith('Hello'); // This is now the scope you need
        $('#newIngredient').modal('hide');
    });
});

答案 1 :(得分:0)

使用以下代码:

$(this).parent().prev().replaceWith('Hello');

答案 2 :(得分:0)

我将传递你的代码逻辑(嵌套点击事件),但你的问题似乎是关于'this'引用(范围):

var self = this;
var newIngredient = $.ajax({
            type: "GET",
            url: '/content/includes/ajax/createNewIngredient.php',
            data: {name: inputName, id_category: inputCategory}
        });

        newIngredient.done(function(result) {
            //PAI.showPage(PAI['PAGE']);
            $(self ).parent().replaceWith('Hello');
            $('#newIngredient').modal('hide');
        });

这是最简单的方法,但更好的方法是使用闭包:

(function(self){
var newIngredient = $.ajax({
                type: "GET",
                url: '/content/includes/ajax/createNewIngredient.php',
                data: {name: inputName, id_category: inputCategory}
            });

            newIngredient.done(function(result) {
                //PAI.showPage(PAI['PAGE']);
                $(self ).parent().replaceWith('Hello');
                $('#newIngredient').modal('hide');
            });

})(this);