1

関数の一部を次に示します。

function updateResponse(question, answer) {
    questionId = 'q'+question;
    document.forms[0].questionId.value = answer;

次のような関数を呼び出します。

<td onClick='javascript:updateResponse(1, 1);'>

更新したいフォーム要素は次のようになります。

<input type='hidden' name='q1' value='' />

Firefox Web コンソールを使用すると、次のようになります。

TypeError: document.forms[0].questionId is undefined

ありがとう!

更新:多くのグーグル検索の後にこれが見つかり、動作します。それでも、これを達成するためのより優雅な方法があるように思えますか?

eval(\"document.forms[0].\"+questionId+\".value = answer;\");
4

1 に答える 1

2

フォームに questionId という名前の入力があることが確実な場合:

document.forms[0][questionId].value

また、グローバル変数を避けるために var を使用する必要があります。

var questionId = 'q' + question;

于 2013-03-28T05:49:18.757 に答える