简体   繁体   中英

JQuery link onClick event sends image - how to get the link object instead?

I have a dropdown list with image and text on each link item. The data tags are on the link which wraps both text and image. When I click on the text, the jQuery.fn.init gives me the a.dropdown-item as I'd expect, but if the image gets clicked, it gives me the image object instead with the a.dropdown-item as parent.

I thought I'd specified the filter correctly in the function call, but obviously not - can anyone point me in the right direction?

Dropdown item contruct:

<a class="dropdown-item" href="/i18n/setlang/" data-nextpage="/ca" data-languagecode="ca">
<img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy">
&nbsp;Català
</a> 

Script start:

$(document).ready(function() {

        $('#languagelist a').on('click', function(event) {
            event.preventDefault();
            let target = $(event.target);
            let nextpage = target.data('nextpage');
            let url = target.attr('href');
            let language_code = target.data('languagecode');
            .....

I thought specifying 'a' would just give me the link object, but when the image is clicked that's what comes as target (without data tags obviously).

Any help much appreciated :)

The issue is because the target of the event is always the element at the bottom of the DOM tree which raised the event, not the element which listened for the event.

To achieve what you require you can either use event.currentTarget or the this reference within the jQuery event handler function, as both of these refer to the element which the listener is attached to. Try this:

 jQuery($ => { $('#languagelist a').on('click', function(e) { e.preventDefault(); // when clicking on the <img /> console.log(this); // = <a /> console.log(event.currentTarget); // = <a /> console.log(event.target) // = <img /> }); });
 img { display: inline-block; width: 20px; height: 20px; background-color: #C00; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="languagelist"> <a class="dropdown-item" href="/i18n/setlang/" data-nextpage="/ca" data-languagecode="ca"> <img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Català </a> </div>

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