2016-11-25 2 views
3

Ich möchte das Vorkommen von bestimmten Wörtern/Phasern in einem HTML-Body zählen. Zum Beispiel in einem Absatz. Das Besondere ist, dass ich zählen möchte, indem ich mit einer Variablen übereinstimme - das bezieht sich auf eine Zeichenkette, nicht auf eine Zeichenkette.Wie man das ausgewählte Wort im HTML-Body durch JavaScript zählt

Der folgende Code gibt nur Nullen zurück.

Vielleicht ist es etwas mit array_values ​​-> wie es es nicht als ein Array sieht. Ich bin ein Anfänger, also ist jeder Hinweis wichtig.

var array_values = document.getElementsByClassName('a'); // <p class="a"> A paragraph that contains some text. 

var chosenWord = document.getElementById("input").value; // a word that i would like to count (how many times it occours in paragraph) 

var count = 0; 
for (var i = 0; i < array_values.length; i++) { 
    if (array_values[i] == chosenWord) 
     count++; 
} 

alert("The word " + chosenWord + "occours " + count + "times"); 

Antwort

1

Eine kleine Änderung und es funktioniert! Die Änderung ist in der Deklaration der ersten Variablen - musste innerHTML hinzufügen - ohne sie erstellen wir ein [HTML OBJECT] das (ich nehme an) kann nicht für diesen Zweck verwendet werden. Danke an Antoine, der einen Trim und Split und ein Array erstellt hat.

var lines = document.getElementById("text").innerHTML.trim().split(" "); // A paragraph that contains some text 

var chosenWord = document.getElementById("input").value; // a word that i would like to count (how many times it occours in paragraph) 

var texts = []; 
    for (var i=0; i < lines.length; i++) { 
    //only push this line if it contains a non whitespace character. 
     if (/\S/.test(lines[i])) { 
      texts.push($.trim(lines[i])); 
     } 
    } 

alert(JSON.stringify(texts)); // the block is creating an array of words from selected DIV. Alert is just to show you an array. 


var count = 0; 
for (var i = 0; i < texts.length; i++) { 
    if texts[i] == chosenWord) 
     count++; 
} 

alert("The word " + chosenWord + "occours " + count + "times"); 
2

Der Code in Ordnung zu sein scheint, das erste, hinzufügen:

var totalIteration = 0; 
var count = 0; 
for (var i = 0; i < array_values.length; i++) { 
    totalIteration ++; 
    if (array_values[i] == chosenWord) 
     count++; 
} 

alert("The word " + chosenWord + "occours " + count + "times in a loop that looped " + totalIteration + " times); 

es Ihnen helfen, wissen, wie die Schleife viele Zeit geschleift, ich glaube, es ist die Quelle ist, die problematique ist:

var array_values = document.getElementsByClassName('a'); 

Was denkst du? Ha können Sie nicht kommentieren ... beantworten Ihre eigene Frage, wenn Sie kommunizieren müssen, und ich werde es in den Kommentaren übertragen

Verwandte Themen