jQuery child of clicked element

后端 未结 3 656
粉色の甜心
粉色の甜心 2020-12-09 17:02

I\'ve got a list of links which have a click event attached to them, I need to get the ID from the child A link. So in the example below if I clicked the first list element

相关标签:
3条回答
  • 2020-12-09 17:40

    To make your code a little neater, lets bind triggers with functions like so: (i suggest you give your UL an ID so it is specific to only elements within that UL)

    $('ul li').bind('click', getAnchorId);
    

    The function that is called (getAnchorId) gets the ID attribute of the children element (a) of the clicked element (ul li) and applies it to a variable (anchorId), and to show its getting the correct info I put the result in an alert.

    function getAnchorId() {
        var anchorId = $(this).children('a').attr('id');
        alert(anchorId);
    }
    

    Now u can do what ever u wish with that variable :)

    hope this helps :)

    0 讨论(0)
  • 2020-12-09 17:47

    You could use the children method:

    $(this).children('a').eq(0).attr('id');
    

    I'm not sure about the syntax, but something like this should work.

    0 讨论(0)
  • 2020-12-09 17:48

    I don't see the sample HTML but

    $(this).find('a:first').attr('id')
    

    would do it (fix a:first selector if it's not what you meant)

    this refer to the element that fired your event

    0 讨论(0)
提交回复
热议问题