2012-04-28 72 views
1

我有問題。我從數據庫加載一些文本。在我的網頁上,我只想顯示本文的第30個字。然後,我會添加一個'閱讀更多'按鈕,將用戶重定向到一個新頁面。所以'jquery擴展插件',它將顯示在同一個div中的剩餘文本,我認爲不適用於我。只顯示第一個#字詞,用jquery

我走到這一步:

$content = $("#blog_1").find(".entryContent").text().split(" "); 
$slicedContent = $content.slice(30); 

我一直在.split和.slice幾個小時瞎搞。但沒有成功。 我甚至不需要「保留」文本的其餘部分,因爲當用戶點擊「詳細信息頁面」上的更多內容時,它會再次加載。從第30個字開始,文字可以從DOM中刪除。 有關顯示一組字符而不是單詞的答案也很有幫助。

感謝advace!

+0

您是否試過閱讀[文檔?](https://developer.mozilla.org/zh/JavaScript/Reference/Global_Objects/Array/slice) – 2012-04-28 19:46:24

回答

3

先回答你的問題,是這樣的:

var test = "I have been messing around with .split and .slice for hours. But no success. I don't even have to 'keep' the remainder of the text, since it will be loaded again when the user will click read more, on the 'detail page'. So onwards from word 30, the text could be removed from the DOM. answers regarding displaying a set number of characters instead of words are also helpful." 
var splittest = test.split(' ') 
splittest.slice(0, 10) 
(returns ["I", "have", "been", "messing", "around", "with", ".split", "and", ".slice", "for"]) 

不會做到這一點,雖然。最好限制文本的數量,然後不必擔心檢測單詞的開始/結尾。它也將使造型更容易,更可預測。

test.slice(0, 300) 
(returns "I have been messing around with .split and .slice for hours. But no success. I don't even have to 'keep' the remainder of the text, since it will be loaded again when the user will click read more, on the 'detail page'. So onwards from word 30, the text could be removed from the DOM. answers regardi") 

再好的一點是限制這個文本服務器端的生成。這只是一個簡單的帶寬浪費,無法發送所有數據。

+0

Finnaly它的工作原理!非常感謝您的回覆。我選擇了你推薦的第二個選項。 – Dogla305 2012-04-28 20:23:58

+0

沒問題,你能將問題標記爲已回答。 – 2012-04-28 20:28:04

+0

我一直在尋找標記爲關閉,但無法找到在哪裏這樣做。 – Dogla305 2012-04-28 20:40:35

0

這樣做:

$slicedContent = $content.slice(0,30) 
+0

感謝您的回覆。有效。儘管它之間用逗號返回。我在下面使用了Andrews anwer,現在我的問題得到了解決。 – Dogla305 2012-04-28 20:25:22