如何解决这个Jquery错误?

时间:2013-10-06 21:19:24

标签: javascript jquery

我已经制作了一些Jquery,你可以用下面这个小提琴看到: http://madaxedesign.co.uk/dev/Test/ http://jsfiddle.net/x82mU/1/

代码:

$(document).ready(function() {
var $root = $('html, body ');
$('.scroll a').click(function(e) {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

// Responsive menu 
$(function() {
    var pull        = $('#pull'),
        menu        = $('nav ul'),
        menuHeight  = menu.height()

    $(pull).on('click', function(e) {
        e.preventDefault();
        menu.slideToggle();
    });

    $(window).resize(function(){
        var w = $(window).width();
        if(w > 320 && menu.is(':hidden')) {
            menu.removeAttr('style');
        }
    });
}); 
 });

但是它遇到了这个错误: 未捕获的TypeError:无法读取未定义的属性“top”

这阻止了我的下一个Jquery工作。

我想知道是否有人能让我知道原因,或者给我一个解决方案?

非常感谢

2 个答案:

答案 0 :(得分:2)

您正试图从href中选择一个菜单项中没有的选择器。

即:

    <li><a href="#">Home</a></li>
    <li><a href="#aboutUs">About us</a></li>
    <li><a href="#">Portfolio</a></li>        
    <li><a href="#">Contact us</a></li>

$(href).offset().top //here offset() of an empty jquery object is undefined.

不是问题,但您可以this.href代替$.attr(this, 'href')

试试这个:

 $('.scroll a').click(function(e) {
    var href = $(this).attr("href"), $el = $(href), top=0; //default top to 0
       if($el.length)  //if there is element matching the href
          top = $el.offset().top; //set the top
    $root.animate({
        scrollTop: top //now scroll
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

<强> Fiddle

答案 1 :(得分:1)

var href = $(this).attr('href');

更新为评论

代表

scrollTop: $(href).offset().top

工作,

href

变量必须是页面上的元素。

所以,如果你的链接是

<a href="#an_id_to_a_div">...</a>

没关系。

jquery dom对象创建

 $(dom_element) 

定位html标签,类,id或现有的Dom对象(窗口,文档..)