简体   繁体   中英

jQuery .attr() method returning undefined

<ul id="footernav">
    <li><a href="javascript:void(0);" id="chat" data-icon="custom" data-transition="none">Tools</a></li>
    <li><a href="javascript:void(0);" id="email" data-icon="custom" data-transition="none">My Ride</a></li>
    <li><a href="javascript:void(0);" id="login" data-icon="custom" data-transition="none">News</a></li>
    <li><a href="javascript:void(0);" id="skull" data-icon="custom" data-transition="none">Cool</a></li>
    <li><a href="javascript:void(0);" id="coffee" data-icon="custom" data-transition="none" class"ui-btn-active ui-state-persist">Contact</a></li>
</ul>

Now I am using this jQuery function to get the id of the li which I have clicked:

$('#footernav li').click(function(){                     
    alert($(this).attr('id'));                    
});

But it returns undefined .

That's because your li don't have IDs

Use this selector instead: $('#footernav li a')

Because you are on the li element not on the a tag.

You should listen to

$('#footernav li a').click(function(){
     alert($(this).attr('id'));

});

This will help you out

$('#footernav li').click(function(){                     
     alert($('a',this).attr('id'));                    
});

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