为什么我不能让这个jQuery代码工作?
问题描述:
我正在尝试使页面滚动以发布具有特定id的例如后21后22等为什么我不能让这个jQuery代码工作?
但它不会工作。请问我的语法有什么问题?
// this is number of posts visible. returns e.g. 2
var posts_visible = <?php echo $news['num_per_page']; ?>;
// this is number of more posts loaded. returns e.g. 2
var posts_more = <?php echo $news['num_per_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我应该是在后。只是不能让它在动画/滚动中工作。请帮我
答
你只需要选择一个字符串,而不是整个$()
函数调用,就像这样:
var thispost = $("#post-" + newposition).position();
$('html,body').animate({
scrollTop: thispost.top + 'px',
scrollLeft: thispost.left + 'px'
},1000);
此外,它可以像上面进行优化......不需要调用.position()
两次得到相同的结果。
答
var thispost = $("#post-"+ newposition);
$('html,body').animate({
scrollTop: thispost.position().top + 'px',
scrollLeft: thispost.position().left + 'px'
},1000);
答
不知道这是否有用,但值得分享。当我要滚动的东西我使用这个插件http://demos.flesler.com/jquery/scrollTo/
+0
+1,scrollTo插件非常棒! :) – deceze 2010-12-13 00:09:50
答
尝试:
var thispost = $("#post-" + newposition);
你不希望创建一个字符串“$("#post-42")
”,你要创建的字符串“#post-42
”,并把它传递给$
函数。
它没有工作。我已经尝试过了。我不知道为什么 – 2010-12-13 00:06:22
@Ahmad - 这是正确的警报,它*是一个对象。如果你想要一些有意义的东西,请使用上面的代码'alert(thispost.top)'。 – 2010-12-13 00:06:56
我想我发现我的错误,我会发布一个更合适的问题。 – 2010-12-13 01:27:19