为什么我不能让这个jquery代码工作?
我试图让页面滚动到具有特定id的post,例如post-21 post-22等
但它不会起作用。 请问我的语法有什么问题吗?
// this is number of posts visible. returns eg 2 var posts_visible = ; // this is number of more posts loaded. returns eg 2 var posts_more = ; // here i calculate the value to know which position should we be at after scroll var newposition = posts_visible + (posts_more * $.cookie('n_more')); // here i am trying to set #post-(thepostnumber) var thispost = '$("#post-' + newposition + '")'; $('html,body').animate({ scrollTop: thispost.position().top + 'px', scrollLeft: thispost.position().left + 'px' },1000);
请注意, alert(thispost)
准确地返回具有正确ID的post。 只是无法让它在动画/滚动中工作。 请帮我
您只需将选择器作为字符串,而不是整个$()
函数调用,如下所示:
var thispost = $("#post-" + newposition).position(); $('html,body').animate({ scrollTop: thispost.top + 'px', scrollLeft: thispost.left + 'px' },1000);
它也可以像上面那样进行优化……不需要两次调用.position()
来获得相同的结果。
尝试:
var thispost = $("#post-" + newposition);
你不想创建一个字符串“ $("#post-42")
”,你想创建字符串“ #post-42
”并将其传递给$
函数。
var thispost = $("#post-"+ newposition); $('html,body').animate({ scrollTop: thispost.position().top + 'px', scrollLeft: thispost.position().left + 'px' },1000);
不确定这是否有用,但值得分享。 当我想滚动某些东西时,我使用这个插件http://demos.flesler.com/jquery/scrollTo/