繁体   English   中英

如何解决这个jQuery错误?

[英]how to solve this Jquery error?

我用下面的小提琴制作了一些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');
        }
    });
}); 
 });

但是它会遇到以下错误:Uncaught TypeError:无法读取未定义的属性“ top”

这使我的下一个Jquery无法正常工作。

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

非常感谢

您试图从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;
});

小提琴

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对象(窗口,文档..)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM