【问题标题】:jQuery CSS Selector combined with "this"jQuery CSS 选择器结合“this”
【发布时间】:2012-02-09 11:08:40
【问题描述】:

我正试图弄清楚这样的事情是否可行。我们得到了 HTML 结构

<a href='#' class='anyLink'>
     <!-- here goes some content-->
    <div class='childElement'><!-- here goes some content--></div>
</a>

我无法使用 ID,因为有很多链接,并且没有定义还有多少链接。所以我的问题是,你们知道我可以做这样的事情吗:

$('a').on("click",function(e){
    $(this +"div").val(); // for example.
});

我想选择该锚点的一个已被点击的子元素或想要获取子元素的值。我也没有任何子元素的 ID,我正在尝试通过 CSS 选择器将事物选择为 td:nth-child(4)。 谁能告诉我这是否可能?

【问题讨论】:

    标签: javascript jquery html jquery-selectors


    【解决方案1】:

    试试

    $('a').on("click",function(e){
        $("div",this).text(); // for example.
    });
    

    【讨论】:

    • 我喜欢并使用第二个建议。
    • 谢谢你帮了我很多忙!
    • @EvilP:如果这有帮助,请务必接受这个答案 :-)
    【解决方案2】:
    $('a').on("click",function(e){
        $(this).children("div").eq(0).html();
    });
    

    【讨论】:

      【解决方案3】:

      您正在寻找一个名为 .children() 的函数。

      不过你也可以试试这样的:

      $('a').on('click', function( e ) {
        $('div', this).val(); // Each div child of this element
        $(this).children('div'); // Each div child of this element
      });
      

      【讨论】:

      • 很抱歉,我很警惕 .children。我必须通过 css-selectors 访问
      • 您可以使用选择器作为子元素的第一个参数。 Live example
      猜你喜欢
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2011-03-03
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多