1

次のコードを使用して、チェックされたラジオ ボタンの値を取得しようとしています。

<html>
<head>
<script type="text/javascript" >
    window.onload = initAll;

    function initAll(){     
        var allAnchors = document.getElementsByName("options");
        for ( var int = 0; int < allAnchors.length; int++) {
            if(allAnchors[int].className == "buttonLink"){
                allAnchors[int].onclick = fetchQuestion;
            }
        }
    }

    function fetchQuestion(){

        var toLoad = this.href;
        var selectedAnswer = "";                
        var allRadio = document.getElementsByTagName("input");

        for(var i = 0;i<allRadio.length; i++){
            if(allRadio[i].checked == true){
                selectedAnswer = allRadio[i].value;
            }
        }       
            alert(selectedAnswer);
                return false;
         }
</script>
</head>
<body>
<input type="radio" name="options" value="optA" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing Operating System is used for Efficeint Resource Sharing Operating System is used for Efficeint Resource Sharing <br/>
             <input type="radio" name="options" value="optB" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing <br/>
             <input type="radio" name="options" value="optC" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing <br/>
             <input type="radio" name="options" value="optD" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing <br/>
<a href="SubmitSheet" class="buttonLink">Submit</a>
        <a href="NextQuestion" class="buttonLink">Next</a>
        <a href="PreviousQuestion" class="buttonLink">Previous</a>
        <a href="PassQuestion" class="buttonLink">Pass</a>
</body>
</html>

ここで私が使用した場合document.getElementByTagName("input")、それは機能しています。しかし、document.getElementByName("options")そうではありません。では、これの何が問題なのですか?? ラジオ ボタンで document.getElementByName を使用できませんか。

4

5 に答える 5

3

おそらく、 document.getElementsByName()を意味します。複数のノードを返す可能性があるため、複数形に注意してください。

于 2011-04-20T16:28:29.390 に答える
2

問題は、「document.getElementByName( "options")」を呼び出している可能性があります

getElementByNameは未定義です

getElementsByNameを呼び出します。これにより、要素コレクションが返されます。

于 2011-04-20T16:29:21.720 に答える
1

document.getElementsByName多くのアイテムが名前を共有できるので、方法は複数形だと思います。単一の要素が必要な場合は、IDを追加してdocument.getElementById名前を使用または使用し、配列を絞り込みます。

javascriptgetElementByNameが機能しない

于 2011-04-20T16:28:00.680 に答える
0

自分で見てください:

javascript:a=document.getElementsByName("options")[0];alert(a.value)

javascript:a=document.getElementsByTagName("input")[0];alert(a.value)
于 2011-04-20T16:36:01.297 に答える
0

この行を変更するだけです:

var allAnchors = document.getElementsByName("options");

代わりにこれに:

var allAnchors = document.getElementsByTagName("a");

そして、コードは期待どおりに動作するはずです。

にはgetElementsByName独自の使用法がありますが、ドキュメント内のすべてのアンカー タグを取得するには、別のメソッドである が必要ですgetElementsByTagName

于 2011-04-20T16:32:15.213 に答える