jquery / js最近的().attr()返回未定义

nub*_*kid 3 html javascript css jquery

我只是最近才开始学习JS,jQuery,HTML和CSS。现在,我正在尝试制作一个页面,单击一个类别类,然后对其进行动画处理,然后重定向到该单击项的链接。

我到处逛逛了很多,得到了.closest(selector).attr('href')东西或父母的东西。我都尝试了,但是我一直对linkto

HTML:

<div class="col-sm-4">
  <div class="mainCon">
    <a href="programs.html">
      <li class="category">
        <img style="height: 150px;" src="programs.png" /><br /> 
        Programs
      </li>
    </a>
  </div>
Run Code Online (Sandbox Code Playgroud)

JS:

$('.category').click(function() {
  $('.mainCon').animate({
    right: '100px',
    opacity: '0',
  }, 500, function() {
    var linkto = $(this).closest('a').attr('href');
    location.href= linkto;
  })
  return false;
});
Run Code Online (Sandbox Code Playgroud)

知道为什么linkto总是返回undefined吗?链接的html文件(programs.html)与我将要来自的页面位于同一目录中,因此我真的不知道出了什么问题。

Sat*_*pal 5

您的HTML无效。li只能是的孩子ul

使用

$('.category').click(function() {
    var self = $(this); //Cache this in a variable
    self.closest('.mainCon').animate({
        right: '100px',
        opacity: '0',
    }, 500, function() {
        var linkto = self.closest('a').attr('href');
        location.href= linkto;
    })
    return false;
});
Run Code Online (Sandbox Code Playgroud)

要么

$('.category').click(function() {
    var self = $(this); 
    self.closest('.mainCon').animate({
        right: '100px',
        opacity: '0',
    }, 500, function() {
        var linkto = $(this).find('a').attr('href');
        location.href= linkto;
    })
    return false;
})
Run Code Online (Sandbox Code Playgroud)