2013-04-25 67 views
0

我這是在有幾個button.enter-match元素長表的末尾運行下面的代碼:如何獲得第一個jQuery對象的父級?

$("button.enter-match") 
.button() 
.on('click', function() { 
    $("form.enter-match").dialog({ 
     modal: true, 
     height: 'auto', 
     width: 200, 
     close: function() { 
      $("form.enter-match input[name='code']").val(''); 
     }, 
     open: function() { 
      $("form.enter-match input[name='code']").val('').focus(); 
     }, 
     buttons: { 
      Set: function() { 
       pid = $(this).parents("[data-pid]").data('pid'); 

       if ($("form.enter-match input[name='code']").val() == '') { 
        alert('Code empty!'); 

        return false; 
       } 

       $.post(
        request_url, 
        { 
         'action': 'set_match', 
         'pid': pid, 
         'code': $("form.enter-match input[name='code']").val() 
        }, 
        function (data) { 
         error_handler(data); 

         if (data['error'] == null) { 
          $("tr#pid-" + pid + " td.code:first div").html('<i>' + $("form.enter-match input[name='code']").val() + '</i>'); 
          $("form.enter-match").dialog('close'); 
         } 
        }, 
        'json' 
       ); 
      } 
     } 
    }); 
}); 

pid = $(this).parents("[data-pid]").data('pid');因爲form#enter_match在的最頂端創建沒有得到pid數據值根據需要在代碼中重新使用文檔。因此,它不會有一個具有[data-pid]屬性的父項,但是,button.enter-match將會。我如何從代碼的$("form.enter-match").dialog()部分中獲取[data-pid]中特定button.enter-match的值?

+2

ID是爲了在文檔中唯一,如果你打算複製一段HTML,你不應該有任何ID。您的選擇器將無法正常工作。你應該給這些元素描述類。 – 2013-04-25 21:11:54

+0

@PaoloBergantino - 您應該是唯一的ID是完全正確的,但指定標記名和ID _will_的選擇器仍然有效。 (一個只使用ID的選擇器只能找到一個,就像'getElementById()'只能找到一個一樣。) – nnnnnn 2013-04-25 21:13:33

+5

@nnnnnn - 不要防守不好的練習/無效的HTML,它不應該完成=> http:/ /stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-types – PlantTheIdea 2013-04-25 21:14:59

回答

0

想不出找到下一個對象的方法,所以我只是將pid = $(this).parents("[data-pid]").data('pid');移動到.on('click', function() {下面的下一個範圍,它在所有情況下解決了這個問題。

感謝所有誰指出我的代碼和類錯誤的編碼做法。我更新了我的編碼風格以反映更好的校長。

相關問題