代码之家  ›  专栏  ›  技术社区  ›  mare

jquery上下文选择

  •  2
  • mare  · 技术社区  · 15 年前

    如果我这样做

    var domElement = $("#id");
    

    返回的元素是一个DIV标记,

    我该怎么做

    domElement.$('div a:nth-child(3)').after(somehtml);
    

    这是一个例子,我想在“domeelement”分区下的第三个链接之后添加一些HTML。

    以上这些似乎不起作用。我有许多例子,其中我已经从整个页面HTML中选择了一个特定的元素,然后我想在该元素的“上下文”中工作。

    在90%的情况下,我希望继续jquery选择、遍历和操作以前从页面中选择的DOM元素,而不是像$(…)那样从整个页面中选择。

    4 回复  |  直到 15 年前
        1
  •  6
  •   user229044    15 年前

    你想要的 .find() : http://api.jquery.com/find/

    var domElement = $("#id");
    domElement.find('div a:nth-child(3)').after(somehtml);
    

    如果计划用多个子选择器链接 domElement ,结束每次使用 查找() 具有 .end() :

    $("#id")
      .find('div')
        .click(function() { alert("#id div"); })
        .find('a.my-class1')
          .click(function() { alert("#id div a.clickable"); })
          .end() // stop working with 'a.my-class1'
        .find('a.my-class2')
          .click(function() { alert("#id div a.my-class2"); }) 
          .end() // stop working with 'a.my-class2'
        .end() // stop working with 'div'
      .click(function() { alert("#id"); });
    

    从概念上讲,您使用.find()深入到DOM中,并使用.end()向上备份DOM。从技术上讲,“降序”和“升序”是不正确的,因为您还可以使用如下函数先上后下遍历 .parent() .closest() ,两者都可以用 () 要返回原始选择器:

    $("#id")
      .parent()
        .click(function() { alert("I'm #id's parent!"); })
        .end()
      .click(function() { alert ("back to #id"); });
    
        2
  •  4
  •   rfunduk    15 年前

    两个选项,使用上下文参数 jQuery function :

    $('div a:nth-child(3)', domElement).after(something);
    

    或(我的喜好)使用 find :

    domElement.find('div a:nth-child(3)').after(something);
    
        3
  •  1
  •   egyedg    15 年前

    试试这个:

    $('div a:nth-child(3)', domElement).after(somehtml);
    
        4
  •  1
  •   cjstehno    15 年前

    尝试

    $('div a:nth-child(3)',domElement).after(somehtml);
    

    上下文是第二个参数。

    祝你好运。