简体   繁体   中英

$(this).attr('href') returns undefined

OK I know there are a lot of posts about JQuery .attr being undefined but I haven't been able to find one that solves or even gives me a hint as to what is going wrong here.

First I have an Ajax request that fills a ul as follows.

$.each(msg,function(key, value){
            ul.append('<li class="fa fa-angle-right cnt-link"><a href="'+key+'">'+value+'</a></li>');
        })

That works fine creates the list and the href tries to go to the non-existent page that is set by the key value.

When the link is clicked though I'm trying to do another AJAX request using that href value but for some reason, I am unable to get the value from it.

$('.cnt-link').click(function(event){
            event.preventDefault();
            var cnt = $(this).text();
            var cntId = $(this).attr('href');               
            console.log(cntId);
            console.log(cnt);
        })

the cnt variable is being set fine so I can't see how it would be a problem with $(this) not referencing the correct object but trying to get the href returns undefined.

I also tried adding the key value using

ul.append('<li class="fa fa-angle-right cnt-link"><a href="#">'+value+'</a></li>').data("cntId", key);

and retrieving it from the clicked item with

var cntId = $(this).data('cntId');

But this also returns undefined so that made me start thinking maybe it is something about $(this) not selecting the correct object.

I'm at my wits end with this and would greatly appreciate some input from anyone who can see what stupid mistake I am making :)

cnt-link is a <li> so it has no href attribute. If you want to get the href inside the li created with the code

ul.append('<li class="fa fa-angle-right cnt-link"><a href="'+key+'">'+value+'</a></li>');

then you might select a s which are children of .cnt-link s instead, and this will refer to an a with a href :

$('.cnt-link > a').click(function(event){

Or, with a handler on the .cnt-link , select the .cnt-link 's .children first to get to the <a> :

$('.cnt-link').click(function(event){
  event.preventDefault();
  var cntId = $(this).children().attr('href');               
  console.log(cntId);
})

 $('.cnt-link').click(function(event) { event.preventDefault(); var cntId = $(this).children().attr('href'); console.log(cntId); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="fa fa-angle-right cnt-link"><a href="somelink">foobar</a></li> </ul> 

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