【问题标题】:What is the second argument in this jquery select statement?这个 jquery select 语句中的第二个参数是什么?
【发布时间】:2016-05-16 14:57:46
【问题描述】:

我看过here。以下语句中的tbl 是什么意思?这意味着什么?

var rows = $('tr', tbl);

【问题讨论】:

    标签: jquery jquery-selectors jquery-context


    【解决方案1】:

    上面的tbl是另一个dom元素。这是作为(可选参数)context 传入的:

    jQuery( selector [, context ] )
    

    ...对于selector,在本例中为'tr'

    source


    所以本质上是这样的:

    $('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](即 context 是可选参数)。选择器不是可选的,所以它不在方括号中。 @user3198603
    【解决方案2】:

    此模式使用 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 上下文

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 2012-04-02
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 2010-11-29
      相关资源
      最近更新 更多