我正在使用JQuery Mobile表:
<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>
现在我正在尝试从下面的JavaScript中提取所有ID并将它们放在一个数组中:
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);
无效。
有什么建议吗?
谢谢!
答案 0 :(得分: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);
});
}
Regex + jQuery的text()
有点资源,因为它在幕后进行了一些DOM操作,而使用data()
或多或少读取属性值