このような機能に入るいくつかの異なるコンポーネントがあります。それらはHTMLとJavascriptに分けられます。まず、テキスト入力ボックスと「送信」というボタンが必要です。次に、ユーザーの入力に基づいた戻り値を表示する方法が必要です。
次に、Javascriptの場合、ユーザーが送信を押したときを検出する方法が必要です。次に、彼の入力を取得し、その入力に対応する配列から値を取得する必要があります。いくつかのフォールバックもいいでしょう。
それでは、HTMLから始めましょう:
<input type="text" id="nameField" placeholder="Please enter your name..."> </input> <br>
<button id="submitName" >Submit</button>
非常に単純なもので、入力と送信ボタンを設定するだけです。ただし、配列からの戻り値を表示する方法も必要なので、<p>
(段落)要素を追加して、後でテキストを表示するように設定できるようにします。
<p id="valueDisplay"> </p>
今Javascriptのために:
var arrayOfValues = {
a: "1",
b: "2",
c: "3",
d: "4",
e: "5",
f: "6",
g: "7",
h: "8",
i: "9",
j: "10",
k: "11",
l: "12",
m: "13",
n: "14",
o: "15",
p: "16",
q: "17",
r: "18",
s: "19",
t: "20",
u: "21",
v: "22",
w: "23",
x: "24",
y: "25",
z: "26"
};
$(document).ready(function() {
// first we attach an onClick handler for the submit button
$("#submitName").click(function() {
// now we need to get the value from our textbox
var name = $("#nameField").val();
// check if the name's length is 0. If it is, we can't do anything with it.
if (name.length === 0) {
alert("Please enter a name.");
// cancel the function completely:
return;
}
// set the name to lower case
name = name.toLowerCase();
// split the name into two words, so that we can do stuff with the first name
name = name.split(" ");
// create an empty string to hold our return value
var returnValue = "";
// here we're going to iterate through the letters of the first name
for (var i = 0; i < name[0].length; i++) {
// name[0] refers to the first part of the name
var curLetter = name[0].charAt(i);
returnValue += arrayOfValues[curLetter];
}
// display the new returnValue in our <p> element:
$("#valueDisplay").html(returnValue);
});
});
上記のJavascriptは少し長いですが、コメントで説明されています(明らかに、私は願っています)。あなたはそれの実用的なバージョンをここで見つけることができます。もちろん、の数字arrayOfValues
はほんの一例です。それらを任意の値に置き換えることができます。数値にならない場合は、引用符で囲んでください。arrayOfValues
ちなみに、これは配列ではありません。連想配列として使用されるオブジェクトです。
最後に、人気のあるJavascriptライブラリjQueryを使用して、上記のスクリプトの問題を少し簡単にしました。あなたの機能はjQueryなしで作成できますが、それは確かに問題をはるかに簡単にします。