【发布时间】:2016-05-16 14:57:46
【问题描述】:
我看过here。以下语句中的tbl 是什么意思?这意味着什么?
var rows = $('tr', tbl);
【问题讨论】:
标签: jquery jquery-selectors jquery-context
我看过here。以下语句中的tbl 是什么意思?这意味着什么?
var rows = $('tr', tbl);
【问题讨论】:
标签: jquery jquery-selectors jquery-context
上面的tbl是另一个dom元素。这是作为(可选参数)context 传入的:
jQuery( selector [, context ] )
...对于selector,在本例中为'tr'。
所以本质上是这样的:
$('tr', tbl);
说 返回我与元素 tbl 中的选择器 'tr' 匹配的所有内容。
给定
<table>
<tr>first</tr>
<table>
<table id="test">
<tr>second</tr>
</table>
这会返回不同的结果:
//context is global
$('tr') => first & second
//restrict the context to just the second table
//by finding it and passing it into the selector
var tbl = $('#test');
$('tr', tbl) => just second
【讨论】:
jQuery( selector [, context ] 中选择器写为selector [ 而上下文写为context ]?我敢肯定这背后一定有一些想法?
[,context](即 context 是可选参数)。选择器不是可选的,所以它不在方括号中。 @user3198603
此模式使用 jQuery 上下文。您的查询用于查找表中的行。
var tbl = $("table#tableId"); // this line provides the context
var rows = $("tr", tbl); // finding all rows within the context
这相当于写
var rows = tbl.find("tr")
在 SO Question here 中有很好的解释使用 jQuery 上下文
【讨论】: