JavaScript 单选按钮和事件处理

JavaScript Radio Buttons and event handling

本文关键字:事件处理 单选按钮 JavaScript      更新时间:2023-09-26

我正在尝试设置一本带有问题的交互式小册子。

我在表格中设置了一个示例问题,该表格有一个单选按钮来选择正确答案。

但是,当我运行脚本

时,警报框(测试)我设置会立即运行并且脚本为空。

确切的错误

Uncaught TypeError: Cannot set property 'onclick' of 
nullinteractive.js:34 mainQuestionOneinteractive.js:38 
(anonymous function)

我的代码

.HTML

    <section class="question-one">
        <h4>Question 1</h4>
        <p>
            Which <stong>one</stong> of the following statements best describes the function of bookkeeping?
        </p>
        <table border="1">
            <tbody>
                <tr>
                    <td>
                        A form of internal accounting providing finanical information at a time and in a format which makes it useable by management for the purpose of planning and controlling a business
                    </td>
                    <td>
                        <input type="radio" name="question-one" id="question-one"/>
                    </td>
                </tr>
                    <td>
                        The mechanistic system of processing and recording the day-to-day financial transactions of a business
                    </td>
                    <td>
                        <input type="radio" name="question-one" id="question-two"  />
                    </td>
                </tr>
                </tr>
                    <td>
                        The mechanistic system of processing and recording the day-to-day financial transactions of a business
                    </td>
                    <td>
                        <input type="radio" name="question-one" id="question-three" />
                    </td>
                </tr>
            </tbody>
        </table>
    </section>

JavaScript

/*--------------------------------------------
QUESTION ONE - LOGIC
----------------------------------------------*/
function mainQuestionOne() {
    var questionOne;
    var questionTwo;
    var questionThree;
    questionOne = document.getElementById('question-one');
    questionTwo = document.getElementById('question-two');
    questionThree = document.getElementById('question-three');
    questionOne.onclick = alert('test');
    questionTwo.onclick = alert('test2');
    questionThree.onclick = alert('test3');
}
mainQuestionOne();
你可以

function() {...}包裹你的alert()

function mainQuestionOne() {
    var questionOne = document.getElementById('question-one');
    questionOne.onclick = function() { alert('test'); }
}
mainQuestionOne();

JSFiddle Link

试试这段代码

问题1

哪 一 以下陈述最能说明簿记的功能?

一种内部会计形式,一次提供财务信息,其格式可供管理层用于规划和控制业务 处理和记录企业日常财务交易的机械系统 处理和记录企业日常财务交易的机械系统
<script type="text/javascript">
    function que1() {
        alert('test1');
    }
    function que2() {
        alert('test2');
    }
    function que3() {
        alert('test3');
    }
</script>

单选按钮的调用函数"onclick"事件