2013-05-02 38 views
2

我有一段JavaScript代碼,我試圖去聲明前面的元素。目前我在兩個相互之間有兩個onclick函數。選擇上一個「this」元素

$('#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'); 

任何想法?

+1

以前是什麼?你可以顯示你的標記。 – 2013-05-02 11:42:19

+2

您是否知道每次單擊'formIngredient'時您在點擊事件中創建'createNewIngredient'的新處理程序? – 2013-05-02 11:42:22

+0

這些嵌套的點擊處理程序看起來有問題(但與您在ajax回調中的「this」問題無關)。 – Bergi 2013-05-02 11:45:35

回答

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'); 
    }); 
}); 
+0

太棒了。這做到了。謝謝。 – Freddy 2013-05-02 11:49:42

+0

沒問題,樂意幫忙。 – 2013-05-02 12:00:27

+0

我會避免使用'self'作爲變量名稱。 – Shikiryu 2013-05-02 12:54:57

0

使用下面的代碼:

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

我會通過你的代碼邏輯(點擊嵌套事件),但你的問題似乎有關「這個」參考(作用域):

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

謝謝。不能更好:) – Freddy 2013-05-02 11:57:53

相關問題