以下代碼創建一個網頁表單。它要求用戶在輸入框中輸入一個字符,然後在另一個框中輸入一個句子。然後,用戶應該能夠點擊一個按鈕來計算該字符出現在第二個輸入框中輸入的句子中的次數。該句子應該只包括字母。我遇到的問題是,我收到一條錯誤消息,說我在框中輸入了非字母,儘管我只輸入了字符!如何統計字符串中字符的出現
任何想法爲什麼發生這種情況請!
這裏是我的HTML/JavaScript代碼:
//<![DATA[
'use strict';
function updateForm(id) {
var letter = "";
var sentence = "";
var occurencies = 0;
var form = document.getElementById(id);
letter = form.box1.value;
sentence = form.box2.value;
for (var i = 0; i < sentence.length; i++)
if (sentence.charAt(i) == letter)
occurencies++;
form.box3.value = occurencies;
}
function isAlphabet(elem, helperMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
} //-->
body {
background-color: lightblue;
}
form {
width: 500px;
margin: 0 auto;
}
h4 {
font-family: sans-serif;
font-size: xx-large;
text-align: center;
}
h1,
h2,
h3 {
font-family: sans-serif;
font-style: italic;
font-size: large;
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
font-style: italic;
}
input[type="button"] {
background: #B9DFFF;
color: #fff;
border: 10px solid #eee;
border-radius: 30px;
box-shadow: 10px 10px 10px #eee;
position: absolute;
left: auto;
}
input[type="button"]:hover {
background: #016ABC;
color: #fff;
border: 5px solid #eee;
border-radius: 30px;
box-shadow: 10px 10px 10px #eee;
}
<form action="#" id="boxes">
Box 1:
<input type="text" name="box1" value="" placeholder="Enter a single
letter" maxlength="1" />
<li class="rq">Only alphabet letters are allowed.</li>
<br />Box 2:
<input type="text" name="box2" value="" placeholder="Enter a sentence" />
<br />Result:
<input type="text" id="letters" name="box3" readonly />
<br />
<input type="button" name="update" value="Update" onclick="isAlphabet(document.getElementById('letters'), 'Only Letters are allowed')" />
</form>
你正在做的是字母在輸出領域,而要做到這一點就在句子填入現場 – Glubus