如何使用 jQuery .each() 查找孩子的孩子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7954436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use jQuery .each() to find a child's children?
提问by mmcglynn
Given many TABLE tags on a page, how do I select the TD childred on a selected table.
给定页面上的许多 TABLE 标签,如何在选定的表上选择 TD 子项。
This is logical, but fails with this error:
这是合乎逻辑的,但因以下错误而失败:
Error: uncaught exception: Syntax error, unrecognized expression: [object Object]tr
My code
我的代码
$(document).ready(function () {
var selectedTable = $('table').eq('9');
$(selectedTable).css('border','10px solid green');
$(selectedTable + 'tr td').each(function(i) {
$(this).css('border','10px solid blue');
});
});
采纳答案by SLaks
selectedTable
is a jQuery object, not a string.
You can't use it in a selector.
selectedTable
是一个 jQuery 对象,而不是一个字符串。
您不能在选择器中使用它。
Instead, you need to use jQuery's traversal API:
相反,您需要使用 jQuery 的遍历 API:
selectedTable.find('tr td')
回答by jbabey
$(selectedTable).find('td').each(function (index, element) {
...
});
回答by ScottE
selectedTable.find('tr td').each(function(i) {
$(this).css('border','10px solid blue');
});
You can also chain like the following:
你也可以像下面这样链接:
selectedTable.css('border','10px solid green').find('tr td').each(function(i) {
$(this).css('border','10px solid blue');
});
Also, you don't need to use $(selectedTable) again as your selector already returns a jquery object.
此外,您不需要再次使用 $(selectedTable) ,因为您的选择器已经返回了一个 jquery 对象。
回答by Bojangles
Use .find()
to get the children of the table. The problem you're having is that selectedTable
isn't a selector string, but an object. You can't concatenate an object with a string, which is why you get your error.
使用.find()
来获取表的孩子。您遇到的问题selectedTable
不是选择器字符串,而是一个对象。您不能将对象与字符串连接起来,这就是您收到错误的原因。
This should work fine:
这应该可以正常工作:
$(document).ready(function () {
var selectedTable = $('table').eq('9');
$(selectedTable).css('border','10px solid green');
$(selectedTable).find('tr td').each(function(i) {
$(this).css('border','10px solid blue');
});
});