简体   繁体   中英

How to get which link was clicked in jQuery

I want to get the text $(el).text() from a block of multiple links and assign it to HTML input. I'm using Laravel and Jquery.

My Blade template is a separate component that is generated from some data.

<div class="some-class" id="some-id">
    <ol>
        @foreach ($data as $el)
            <li>
                <a href="javascript:;" class="some-a-class">{{ $el['name'] }}</a>
            </li>
        @endforeach
    </ol>
</div>

Then I'm looking at how to catch the click of the link, get the text from it, and pass it to the input.

My jQuery code looking like:

$('#some-id > a').on('click', function () {
    console.log(this.text());
})

From multiple sources found that the way above ^ should be working, but for me, it doesn't even understand that I have clicked.

Maybe is there another way to get the clicked link name?

Thank you.

Change your jquery selector to this:

$('#some-id ol li a')

Right now you are trying to select a elements that their parent element is #some-id , which is not the case. There is a difference between Children of an element ( div > p ) and Descendants of an element ( div p ).

@AlwaysHelping 评论是我正在寻找的评论。

$(document).on('click', '#some-id a', function () {console.log($(this).text());})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM