2013-06-06 39 views
1

我使用jQuery Mobile的表:JQuery的第獲得或TD文本從TR空的空間問題

<table data-role="table" id="productTable" data-mode="reflow" class="tablesorter ui-responsive table-stroke my-custom-breakpoint"> 
       <thead> 
        <tr> 
         <th data-priority="1"> 
          ID 
         </th> 

         ... 

        </tr> 
       </thead> 
       <tbody> 
        <asp:Repeater ID="productRepeater" runat="server"> 
         <ItemTemplate> 
          <tr class="item"> 
           <th class="id"> 
            <%# Eval ("ID")%> 
           </th> 

           ... 

          </tr> 
         </ItemTemplate> 
        </asp:Repeater> 
       </tbody> 
      </table> 

現在我試圖提取所有的ID形成,並把它們在我的JavaScript數組如下:

function viewSelectedDocuments() { 
    var selectedIDs = [];  
    $("tr.item").each(function() { 
     var id = $(this).children().eq(0).text(); 
     var id = $.trim(id); 
     alert(id); 
     selectedIDs.push(id); 
    }); 
} 

單擊按鈕時調用此函數。然而在var id我沒有得到我期待的。相反,從細胞的文字說"1"我越來越

"ID 

            1" 

,是的 - $.trim(id);不工作。

有什麼建議嗎?

謝謝!

+1

'var id = $(this).children()。eq(0).text()。replace(/ \ s +/g,「」) – Ramunas

+0

謝謝, @Ramunas!現在它工作:)「ID 1」 –

+0

@Ramunas如果你可以複製你的代碼作爲答案,以便我可以接受它作爲問題的答案。謝謝! –

回答

3

這可能有一點正則表達式可以輕鬆解決:

var id = $(this).children().eq(0).text().replace(/\s+/g, " "); 

我的建議是提高結構的位:

<ItemTemplate> 
    <tr class="item" data-id='<%# Eval ("ID")%>'> 
     <th class="id"> 
      <%# Eval ("ID")%> 
     </th> 
     ... 
    </tr> 
</ItemTemplate> 

function viewSelectedDocuments() { 
    var selectedIDs = [];  
    $("tr.item").each(function() { 
     var id = $(this).data('id'); 
     //var id = $.trim(id); <-- no need to trim anymore 

     // depending on what your <%# Eval ("ID")%> you might still need regex 
     // id = id.replace(/\s+/g, " "); // uncomment if needed 
     alert(id); 
     selectedIDs.push(id); 
    }); 
} 

正則表達式+ jQuery的text()是一點資源密集型的,因爲它在後臺執行一些DOM操作,whil使用data()或多或少讀屬性值