开发者

How do I combine 'this' with a first-child selector?

I'm trying to combine 'this' with div:first-child to get the html value of a 开发者_Python百科hidden div that makes up the body of an anchor tag. How should this work?

$('a').click( function(){
  $(this + "div:first-child").html();
}


Try this out:

$('a').click( function(){
  $("div:first-child", this).html();
}

It selects the html of the "div:first-child" inside of the link


It's worth pointing out, first, that a div is a block-level element, and as such is invalid within an inline-element (such as an a). That said, it might be worth amending your selector:

$('a').click( function(){
  $(this).find("div:first-child").html();
}

Or:

$('a').click( function(){
  $(this).find("div:hidden").html();
}

I've not changed your elements from div to span, though I strongly suggest that you should. Incidentally, using context-selectors ($('div:first-child',this)) calls find() internally anyway, converting it to: $(this).find('div:first-child').

References:

  • find().
  • :hidden-selector.
  • jQuery's context-selector.


Use

$(this).children("div:first-child").html();

To access child elements within the anchor-link element.


$('a').click( function(){
  $("div:first-child", this).html();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜