加载页面时触发点击

Trigger onclick when page is loaded

本文关键字:加载      更新时间:2023-09-26

我有一组带有onclick事件的单选按钮,该事件隐藏/显示网站的某个区域。 onclick 还会启用/禁用 spry 验证。

点击工作得很好! 但是,不确定如何在加载页面并将单选按钮标记为已单击时触发 onclick。

例如,用户可以在主页上选择单选按钮。 然后,在表单流程的稍后阶段,用户可能希望编辑他们输入的输入。 然后,我将检查用户在主页上选择的单选按钮。 由于用户尚未单击单选按钮,因此隐藏区域仍保持隐藏状态。

window.onready=function()
{    
    if(document.getElementById('yourRadioButtonId').checked) {
       //call your function, that you want to be triggered, as you will have the same call back function bounded for your onclick event    
}

window.onready=function()
    {    
        var radioButton=document.getElementById('yourRadioButtonId');
        if(radioButton.checked) {
           radioButton.click();
        }
    }

注意:并非所有浏览器都允许以这种方式模拟事件。请参阅触发器方法的 jQuery 源代码,以了解如何处理所有浏览器怪癖。

处理此问题的最佳方法是编写一个帮助程序函数。稍后,此帮助程序函数可以由 onClick(单选按钮)和 onLoad(正文元素)事件调用。此函数将获取单选按钮的值,并根据结果执行操作。

例如:

function handleRadioButtonStateAction() {
     var radioButtons = document.getElementsByName('theRadioButtonName');
     for (var x = 0; x < radioButtons.length; x ++) {
         if (x == yourDesiredButton && radioButtons[x].checked) {
             //do action
         }
   }
}