使用Javascript和单选按钮显示文本文件

时间:2019-01-09 06:39:26

标签: javascript html

如何仅使用javascript和单选按钮在下一页显示1.txt或2.txt文件。

<input type="radio" name="choice">File 1
<input type="radio" name="choice">File 2<br>
<input type="submit" value="Read"><br>

预先感谢您:D

1 个答案:

答案 0 :(得分:-1)

假设这些文件与您的页面位于同一文件夹中,则一个非常简单的解决方案是:

HTML:

<input class="myRadio" type="radio" name="choice" value="1.txt">File 1
<input class="myRadio" type="radio" name="choice" value="2.txt">File 2<br>
<input onclick="myFunction()" type="button" value="Read"><br>

JavaScript:

function myFunction(){
    var radios = document.getElementsByClassName('myRadio'); // get array of all radio buttons

    for (var i = 0; i < radios.length; i++){ // loop through array of radio buttons
        if (radios[i].checked){ // check if current button is checked
            window.location.href = radios[i].value; // simulate clicking a link with button value as href
        }
    }
}