单选按钮onclick的条件,如果为false,不要检查

condition on radio button onclick, if false don't check

本文关键字:false 检查 如果 onclick 条件 单选按钮      更新时间:2023-09-26

onclick的一个单选按钮,我必须检查一个条件,如果为真,我必须检查它或恢复到原来的状态,

<input type="radio" name="test" id="radio0" onclick="myFunction()" checked /> 
<input type="radio" name="test" id="radio1" onclick="myFunction()" /> 
<input type="radio" name="test" id="radio2" onclick="myFunction()" /> 

JS

globalCondition = false;
function myFunction()
{
   if(globalCondition)
   {
      //some codes and it will check clicked radio button anyway 
   }
   else
   {
       return false; // i tried this but its not working
      /*here i don't want to check clicked radio button, and previously
       checked button should be checked*/ 
   }
}

正如我在注释return中所说的,函数中不会做任何事情,因为您没有在内联代码中返回函数值。

虽然提供的其他解决方案是正确的,但为了使您的代码不引人注目,您根本不应该使用内联JS(删除onclick=)。

我意识到这个问题没有标记jQuery,但也许它应该是:相反,在onclick你应该使用jQuery事件处理程序,只选择一组单选按钮。

JSFiddle: http://jsfiddle.net/TrueBlueAussie/KVwL3/1/

globalCondition = false;
$(function(){
    $("[name=test]").click(function(e){
       if(globalCondition)
       {
          //some codes and it will check clicked radio button anyway 
       }
       else
       {
           return false;
            // or
            e.preventDefault();
           /*here i don't want to check clicked radio button, and previously
           checked button should be checked*/ 
       }
    });
});

指出:

DOM就绪事件:

$(function(){ YOUR CODE HERE });$(document).ready(function(){ YOUR CODE HERE});的快捷方式

<

选择器/strong>

如果属性[]选择器=值包含特殊字符,则需要加引号:

$('[name="IstDynamicModel[SD_WO_CREATE]"]')

有许多选择器将只选择三个单选按钮。由于这是一个简单的一次性连接,在启动时,任何选项之间都没有实际的速度差异,但您通常会尝试使用特定的选择器,以便使用浏览器可用的各种查找表:

$('input[type=radio][name="IstDynamicModel[SD_WO_CREATE]"]')

这将稍微快一些,因为它将把最慢的检查(name=)减少到只有radio input s。

try this:

globalCondition = false;
function myFunction(e)
{
   if(globalCondition)
   {
      //some codes and it will check clicked radio button anyway 
   }
   else
   {
       e.preventDefault();
       return false; // i tried this but its not working
      /*here i don't want to check clicked radio button, and previously
       checked button should be checked*/ 
   }
}

像这样使用

<input type="radio" name="test" id="radio1" onclick="return myFunction()" /> 
javascript

globalCondition = false;
function myFunction(e)
{
   if(globalCondition)
   {
      //some codes and it will check clicked radio button anyway 
     return true;
   }
   else
   {
       return false; // i tried this but its not working
      /*here i don't want to check clicked radio button, and previously
       checked button should be checked*/ 
   }
}