表行的 jQuery 条件选择器
我有一个包含数据的表:
;项目订单代码 价格
我正在使用 jQuery 处理表格,需要查找订单代码:
$.each($('.productList tbody tr'), function() {
var orderCode = $(this).find('td:eq(1)').html().trim();
// do stuff
});
如果没有产品,表格会显示一条消息:
;没有可显示的产品
上面的行导致 jQuery 函数崩溃。使用条件选择器忽略“无产品”行的最可靠方法是什么?是否有 colspan="1"
或 colspan is not set
或任何需要的选择器?
I have a table with data in:
<td> item </td><td> order code </td><td> price </td>
I'm processing the table with jQuery which needs to find the order code:
$.each($('.productList tbody tr'), function() {
var orderCode = $(this).find('td:eq(1)').html().trim();
// do stuff
});
If there are no products, the table shows a message:
<td colspan="3"> There are no products to display </td>
The above row causes the jQuery function to bomb out. What's the most robust way to use a conditional selector to ignore the "no products" row? Is there a selector for colspan="1"
or colspan is not set
or whatever it would need to be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样:
这只会选择
元素,其
是其父元素的第二个子元素。 (
nth-child
选择器 是基于 1 的)Like this:
This will only select
<tr>
elements that have a<td>
that is the second child of its parent. (thenth-child
selector is one-based)不要细化你的选择器,它不会很好地扩展,因为 jQuery 必须评估每个子元素。而是避免错误...
Don't refine your selector, it won't scale well because jQuery will have to evaluate every child element. Avoid the error instead...
如果您可以更改生成表格的方式,那么使用类是一个更清晰的解决方案:
然后仅选择所需的类:
这也将提高您使用 CSS 设计表格样式的灵活性,并且如果您添加或重新排序,您的代码也不会中断列。
If you can change how you generate the table, using classes is a cleaner solution:
Then select only the desired class:
This will also give you increased flexibility in styling the table with CSS, and your code won't break if you add or reorder columns.
您可以测试有多少个 td:
You could test how many
td
s there are:使用
.attr()
方法。查看 api.jquery.com,这应该可以帮助您弄清楚如何从单元格中获取 colspan 属性。Use the
.attr()
method. Check out api.jquery.com and that should help you be able to figure out how to get the colspan attribute from your cells.对 SLAks 编写的内容进行更多过滤
$("table tbody tr td:nth-child(2):contains('code')")
More filtration to what SLaks has written
$("table tbody tr td:nth-child(2):contains('code')")