jQuery: Find the text of a list item that contains a nested ul

后端 未结 7 1605
暖寄归人
暖寄归人 2020-12-10 12:49

I have the following:

  • item1
    • sub1
    • sub2
7条回答
  •  情歌与酒
    2020-12-10 12:53

    you're having a hard time because text() does what it should - returns the text of this and all child elements. The easiest thing to do is to add another tag to every

  • , and use this tag.
    For example:

    • item1
      • sub1
      • sub2

    And then you have a simple selector:

    $("#list li").click(function() {
       alert($(this).find("span").eq(0).text());
    });
    

    or, if possilbe (depending on your style), you may add the event to the span:

    $("#list span").click(function() {
       alert($(this).text());
    });
    

    If you cannot add these s (as you say) you can use jQuery's .contents() to add them for you, similar to what was done here:

    Hide B in A
    B

提交回复
热议问题