我有2个单选按钮和jquery正在运行。
<input type="radio" name="lom" value="1" checked> first
<input type="radio" name="lom" value="2"> second
现在,使用按钮,我可以将onClick设置为运行功能。单击单选按钮时,使单选按钮运行功能的方式是什么?
Answers:
您可以使用.change所需的东西
$("input[@name='lom']").change(function(){
// Do something interesting here
});
从jQuery 1.3开始
您不再需要“ @”。正确的选择方式是:
$("input[name='lom']")
$("input[name='lom']")
$("input[name='lom']").change(function(){ if ($(this).val() === '1') {..... // rest conditional statements based on values here } ;
jquery.self-0a6570c….js?body=1:1464 Uncaught Error: Syntax error, unrecognized expression错误。因此,这不是选择问题。
如果您将无线电放在ID = radioButtonContainerId的容器中,则仍然可以使用onClick,然后检查选择了哪个无线电并相应地运行一些功能:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
这应该很好
$(document).ready(function() {
$('input:radio').change(function() {
alert('ole');
});
});
有几种方法可以做到这一点。无论如何,强烈建议在单选按钮周围放置一个容器,但是您也可以直接在按钮上放置一个类。使用此HTML:
<ul id="shapeList" class="radioList">
<li><label>Shape:</label></li>
<li><input id="shapeList_0" class="shapeButton" type="radio" value="Circular" name="shapeList" /><label for="shapeList_0">Circular</label></li>
<li><input id="shapeList_1" class="shapeButton" type="radio" value="Rectangular" name="shapeList" /><label for="shapeList_1">Rectangular</label></li>
</ul>
您可以按班级选择:
$(".shapeButton").click(SetShape);
或按容器ID选择:
$("#shapeList").click(SetShape);
在这两种情况下,事件都将在单击单选按钮或标签时触发,尽管在后一种情况下很奇怪(通过“ #shapeList”选择),但由于某种原因,在标签上单击会触发两次单击功能,在至少在FireFox中;按班级选择不会这样做。
SetShape是一个函数,看起来像这样:
function SetShape() {
var Shape = $('.shapeButton:checked').val();
//dostuff
}
这样,您可以在按钮上带有标签,并且可以在同一页面上具有多个单选按钮列表,这些列表可以执行不同的操作。您甚至可以通过基于按钮的值在SetShape()中设置不同的行为,使同一列表中的每个按钮执行不同的操作。
最好限制DOM搜索。因此最好也使用父级,这样就不会遍历整个DOM。
非常快
<div id="radioBtnDiv">
<input name="myButton" type="radio" class="radioClass" value="manual" checked="checked"/>
<input name="myButton" type="radio" class="radioClass" value="auto" checked="checked"/>
</div>
$("input[name='myButton']",$('#radioBtnDiv')).change(
function(e)
{
// your stuffs go here
});