2012-09-10 52 views
1

我還在學習jQuery,遇到了一個問題。我有一個有50多行的表格。每個都標有一個ID。將<tr> ID傳遞給jQuery

<tr id="51"> 

此ID是數據庫ID,我需要將它傳遞給jQuery並將其與AJAX請求一起提交。

 $($location).click(function() { 
      var $currentSelection = $(this); 

      // if there is already an input-field in this TD, return... 
      if($currentSelection.find('select').length > 0) 
       return; 

      $currentSelection.html(''); 

      $('<select id="selectLocation" onChange="locationSubmit()"/>') 
       .attr('name', 'location') 
       .append('<option>Location 1</option>', '<option>Location 2</option>', '<option>Location 3</option>') 
       .appendTo(this); 
     }); 

locationSubmit()

function locationSubmit(){ 
      var $selectLocation = $('#selectLocation').val(); 
      var $selectId = $(this).val('tr#id'); //stuck here 
      alert($selectId); 
      $.ajax({ 
       url: '/ajax/training-update.php', 
       data: { 
         action: $selectLocation, 
         courseid: $selectId 
        }, 
       type: 'POST', 
       success: function(output) { 
        alert(output); 
        } 
      }); 
     } 

locationSubmit()警報被返回[對象的對象。如何將tr#id的值傳遞給locationSubmit()並通過AJAX發送?

編輯 - HTML

<tr id="51"> 
    <td><a href="/link/goes/here.php?course_id=5&id=51">course name</a></td> 
    <td> 
     <span class="rowStartDate" id="rowStartDate151">09/10/12</span> - 
     <span class="rowEndDate" id="rowEndDate151">09/14/12</span> 
    </td> 
    <td class="location">Location 2</td> 
    <td class="status">open</td> 
</tr> 
+0

開始以數字的'id'是,除非你在技術上無效正在使用HTML5。對於HTML4,[HERE](http://www.w3.org/TR/html4/types.html#type-id)是命名規則。確保通過[W3C Validator](http://validator.w3.org/)運行您的HTML頁面。 – Sparky

+0

檢查我的新編輯,它可能是正確的或在梯子上的一步? –

+0

你能發佈一個鏈接嗎? – howderek

回答

3

那麼,有什麼好的答案嗎?

測試此:

$($location).click(function() { 
     var $currentSelection = $(this); 

     // if there is already an input-field in this TD, return... 
     if($currentSelection.find('select').length > 0) 
      return; 

     $currentSelection.html(''); 

     $('<select id="selectLocation"/>') 
      .attr('name', 'location') 
      .append('<option>Location 1</option>', '<option>Location 2</option>', '<option>Location 3</option>') 
      .appendTo(this); 
    }); 

以及與此更換你的函數:

$('body').delegate('#selectLocation', 'change', function(){ 

     var $selectLocation = $(this).val(); //Edited here also 
     var $selectId = $(this).closest('tr').attr('id'); //edited here 
     alert($selectId); 
//The AJAX here   
}); 

而且你看,你的功能是通過委託,這似乎工作的偉大不見了,取而代之! .delegate()是一個非常好的函數,它始終在工作,即使元素是在DOM準備好之後創建的。它一直在收聽

編輯 檢查第二個代碼部分。

+0

這將返回「未定義」。我有'.click'函數創建'',這可能會導致問題嗎? –

+0

以及如何定義'$ location'? –

+0

它在我的腳本的頂部使用'var $ location = $(「。location」);' –