When the user clicks the "Statistics" button, the character with the most occurrences in the text box pops up in the window and displays the number of occurrences
The effect when clicking the statistics button is shown in the figure:
Implementation code:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script type="text/javascript"> window.onload = function () { //Get form object var form = document.getElementById("myform"); //Register the click event for the "statistics" button form.btn.onclick = function () { //Get the value in the text box var txt = form.name.value; //Define an empty js object to save all characters in the text space and the number of occurrences var json = {}; //Transfer the value in the text box, that is, the string saved in the txt variable for (var i = 0; i < txt.length; i++) { //Extract the sub-character subscripted by i in the txt string and determine whether the json object has not defined the attribute name as the attribute given to the character if (!json[txt.charAt(i)]) { //Define the attribute (represents the character that appears in the text box) and assign it to 1, representing the number of times the corresponding characters of the attribute appears in the text box json[txt.charAt(i)] = 1; } else { //After already defined, add 1 to the value of the attribute, that is, add 1 to the number of times the character corresponding to the attribute appears in the text box json[txt.charAt(i)]++; } } //Define two variables var maxnum = 0;//Denote the number of times the character with the most occurrences in the text box is 0 var char = "";//Denote the character with the most occurrences in the text box by default is empty //Travel the attribute value of the json object for (var i in json ) { if (json[i]>maxnum) { //If the value of the json attribute is greater than maxnum (that is, ask the characters corresponding to the attribute again in this box, then assign it to maxnum and assign its attribute name to char maxnum = json[i]; char = i; } } alert(The most common characters in the "text box are: " + char + " The number of times they appear are: " + maxnum); } }; </script> </head> <body> <form id="myform"> <input type="text" name="name" value="123" /> <input type="button" name="btn" value="statistics"/> </form> </body> </html>JS object attributes can be used in a comprehensive application of js objects such as features added later, traversal of object attributes, etc.
For knowledge about js, please refer to the related operations of javascript objects.
The above JavaScript advanced exercises and simple example analysis are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.