必要なときに webAdress の長さを確認すると、見つからないのに長さが返されないのはなぜですか?
<script type="text/javascript">
function myFunction() {
var webAdress = document.getElementById('webAdress');
alert(String(webAdress.legnth));
}
必要なときに webAdress の長さを確認すると、見つからないのに長さが返されないのはなぜですか?
<script type="text/javascript">
function myFunction() {
var webAdress = document.getElementById('webAdress');
alert(String(webAdress.legnth));
}
これは正しくdocument.getElementById
、存在する場合は常に単一の要素を返します。複数の要素に同じ ID を使用しないでください。
webAdress
配列ではなくdom要素です。
特定の要素の長さを確認したい場合は、クラスを使用します。
var webAdress = document.getElementsByClassName('webAdress');
alert(webAdress.length);
webAdress のコンテンツの長さを確認する場合:
var webAdress = document.getElementById('webAdress');
alert(webAdress.innerHTML.length);
使用可能なコントロールの数を取得したい場合、その名前はwebAdressであり、以下の関数が正しいです。ただし、webAdressフィールドの文字列の長さを取得する場合は、以下に示すようにjavascirpt関数の値属性が必要です。
function myFunction() {
var webAdress = document.getElementById('webAdress');
alert(String(webAdress.legnth));
}
function myFunction() {
var webAdress = document.getElementById('webAdress').value;
alert(String(webAdress.legnth));
}
<input type="text" id="webAdress">
<input type="button" value="check" onClick="myFunction()">
function myFunction() {
var webAdress = document.getElementById('webAdress').value;
alert(webAdress.length);
}
この例を試すと、スペルに問題がありました。
更新:同じスクリプトをフィドルに追加しましたhttp://jsfiddle.net/sameerast/Rk7ht/1/