2013-05-16 22 views
0

我有一個包含幾個textareas(100)的html工作表,它們都具有相同的「編輯」ID。在html工作表上的多個textareas計數單詞

我的問題是,我想指望所有的每一個人單獨的話......

我曾嘗試一些代碼片段,我認爲做工精細第一textarea的,但停止工作在互聯網上找到第二個...

我是一個JavaScript的總新手,我甚至不知道從哪裏開始。所有的幫助非常感謝。

感謝

+2

如果它們都具有相同的id,你這樣做是錯誤的。 –

+2

@Jay Blanchard。 ID是唯一的,爲一個以上的元素使用一個類 – Alex

回答

1

當你通過ID查找一個元素時,它只會返回一個元素,所以你的方法不適用於多個元素。你可以做的是迭代id。例如,元素1的id =「edit1」,元素2 =「edit2」,元素100 =「edit100」等等。通過這種方式,你可以很容易地訪問所有的人都用一個簡單的for循環:

var rootID = "edit"; 
var totalWordCount = 0; 
for (var i=0; i<100; i++) { 
    var textElement = document.getElementById(rootID + i); 
    var textBoxContents = textElement.value; 

    // Count the words in one textbox. 
    var textBoxWordCount = 0; 
    // These are optional, they are there to account for new lines or double spaces 
    // and will help make your word count more accurate. 
    textBoxContents = textBoxContents.replace(/(^\s*)|(\s*$)/gi,""); 
    textBoxContents = textBoxContents.replace(/[ ]{2,}/gi," "); 
    textBoxContents = textBoxContents.replace(/\n /,"\n"); 
    // This splits up words and counts them based on whether there is a space 
    // between them or not. 
    textBoxWordCount = textBoxContents.split(' ').length; 

    // Add this number of words to the total. 
    totalWordCount += textBoxWordCount; 
} 

// totalWordCount now holds the total number of words in all your boxes! 
+0

我該怎麼做? - > //計算單詞,將單詞添加到totalWordCount或任何其他你想要對他們做的事情。 – Alex

+0

我在我的答案中增加了一些實現信息,希望有助於! – exxodus7

0

正如HTML specification提到的ID必須是唯一的。你的JavaScript代碼失敗了,因爲它符合這一點。在匹配第一個ID之後,沒有理由繼續檢查元素。

0

一旦你有你的ID排序,這是非常重要的,使用下面的小提琴幫助 - http://jsfiddle.net/dXcLH/1

在這個小提琴中,它只是遍歷每個textarea並在列表中設置一個值。

0

你可以嘗試這樣的事:

// tas is all your textareas 
var tas= document.getElementsByName("textareas"), 
    // or document.getElementsByTagName("textarea") 
i,arr=[]; 
for(i=0;i<tas.length;i++){ 
    arr.push({ 
    textareaName:tas[i].name, 
    //rough word count 
    wordCount:tas[i].value.split(/\b[^\d\w\-]+\b/ig).length 
    }]; 
} 
console.log(arr); 

檢查這個代碼出在Chrome中,按F12,看看ARR變量在控制檯中,你可以點擊它來檢查它的值。

0

您設置一類所有文字區域,而不是一個ID你可以嘗試以下後:

function countAllWords(){ 
    var result = 0; 
    $(".edit").each(function(){ 
    var wordcount; 
    wordcount = $(this).yourCountingFunction(); 
    result = result + wordcount; 
    }); 
    return result; 
}