点击一个单选按钮我必须检查一个条件,如果我必须检查它或恢复到相同的旧状态,
HTML
<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*/
}
}
答案 0 :(得分:1)
试试这个:
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*/
}
}
答案 1 :(得分:1)
像这样使用
<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*/
}
}
答案 2 :(得分:1)
正如我在评论return
中所说的那样,函数不会做任何事情,因为你没有在内联代码中返回函数值。
虽然提供的其他解决方案是正确的,但为了保持代码不引人注目,您根本不应该使用内联JS(删除onclick=
&#39; s)。
我意识到这个问题没有被标记为jQuery
,但也许它应该是:相反在onclick
上你应该使用jQuery事件处理程序,只选择一组单选按钮。
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});
<强>选择器强>
如果属性[]
选择器=
值包含特殊字符,则需要引用它:
$('[name="IstDynamicModel[SD_WO_CREATE]"]')
有任意数量的选择器只会选择三个单选按钮。由于这是一个简单的一次性连接,在启动时,任何选项之间都没有真正的速度差异,但您通常会尝试以可能使用浏览器可用的各种查找表的方式使选择器具体:
$('input[type=radio][name="IstDynamicModel[SD_WO_CREATE]"]')
这会稍快一些,因为它会将最慢的检查(name=
)减少到radio
input
。