2010-12-12 107 views
0

我正在嘗試使頁面滾動以發佈具有特定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我應該是在後。只是不能讓它在動畫/滾動中工作。請幫我

回答

1

你只需要選擇一個字符串,而不是整個$()函數調用,就像這樣:

var thispost = $("#post-" + newposition).position(); 
$('html,body').animate({ 
    scrollTop: thispost.top + 'px', 
    scrollLeft: thispost.left + 'px' 
},1000); 

此外,它可以像上面進行優化......不需要調用.position()兩次得到相同的結果。

+0

它沒有工作。我已經嘗試過了。我不知道爲什麼 – 2010-12-13 00:06:22

+0

@Ahmad - 這是正確的警報,它*是一個對象。如果你想要一些有意義的東西,請使用上面的代碼'alert(thispost.top)'。 – 2010-12-13 00:06:56

+0

我想我發現我的錯誤,我會發佈一個更合適的問題。 – 2010-12-13 01:27:19

0
var thispost = $("#post-"+ newposition); 
$('html,body').animate({ 
    scrollTop: thispost.position().top + 'px', 
    scrollLeft: thispost.position().left + 'px' 
},1000); 
4

嘗試:

var thispost = $("#post-" + newposition); 

你不希望創建一個字符串「$("#post-42")」,你要創建的字符串「#post-42」,並把它傳遞給$函數。

相關問題