2016-05-09 11 views
0

私は死んでしまうはずのようなことをしようとしています。引用符で囲まれたリテラル値が必要な変数getElementByIDを使用しようとしています。同じ検証コードを実行する複数のフィールドがあり、エラーがある場合は問題のあるフィールドに戻ります。他の質問と回答を見ると、私がしようとしていることはうまくいかないと思われるので、より良い選択肢が必要ですが、それは何か分かりません。ここでgetElementByID内の変数を使用してfocus()を設定する

は私が持っているものです:あなたはgetElementByIdを関数に

ORだけ(簡単にIDない値を渡す必要があるため

document.getElementById(FocusMe.id).focus(); 

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>I just want to focus!</title> 
<script> 
// this section of code would validate 3 similar fields 
function FocusFoo(FocusMe) { 
    // validation routine here 
    // on failure, I want to select the field that called the function  
    document.getElementById(FocusMe.value).focus(); 
    // fails because getElementById expects a quoted literal. 
    return false; 
} 
</script> 
</head> 
<body> 
<form id="FooForm" name="FooForm" action="foo.php" method="post"> 
<p>Leave Foo 1 to test focus.</p> 
<p>Foo 1: <input type="text" id="Foo1" name="Foo1" onBlur="FocusFoo(this)"></p> 
<p>Foo 2: <input type="text" id="Foo2" name="Foo2" onBlur="FocusFoo(this)"></p> 
<p>Foo 3: <input type="text" id="Foo3" name="Foo3" onBlur="FocusFoo(this)"></p> 
</form> 
</body> 
</html> 
+2

実際に要素を取得する必要はありません。あなたはすでに 'FocusMe' - ' FocusMe.focus(); 'にそれを持っています。また、 'getElementById()'はリテラルを想定していません。リテラルで作成できる文字列値が必要です。 –

答えて

0
はにあなたの関数を変更し

コメントによって示されるように)

FocusMe.focus(); 
+2

FocusMe.focus()は簡単ではないでしょうか? – nnnnnn

+0

それで論争するつもりはない。 –

+0

私はFocusMe.focus()を使って説明したように関数を変更しましたが、任意のフィールドからタブアウトすると、プロシージャの実行後に次のフィールドがフォーカスを受け取ります。 –

関連する問題