<script type="text/javascript">
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue = $("input[name='gender']:checked").val();
if (radioValue) {
alert("Your are a - " + radioValue);
}
});
});
</script>
<label>
<input type="radio" name="gender" value="male" />Male</label>
<label>
<input type="radio" name="gender" value="female" />Female</label>
我想编辑上面的简单jquery脚本,以接受输入名称(名称=“性别”)作为变量/参数。我怎样才能做到这一点。而不是从字面上说明名称。
HTML:
<label>
<input type="radio" name="gender" value="male" />Male</label>
<label>
<input type="radio" name="gender" value="female" />Female</label>
答案 0 :(得分:0)
该示例将帮助您入门:
$(document).ready(function() {
$("input[type='radio']").click(function() {
var chkType = $('#chkType').val();
var radioValue = $("input["+chkType+"]:checked").val();
if (radioValue) {
alert("Your are: " + radioValue);
}
});
});
.flex-parent{display:flex;}
.flex-child{flex:1;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<h3>1. Click Male/Female radio buttons. Working normally BUT using a variable.</h3>
<h3>2. In the input box, change "gender" to "size" and click change button, then click the Tall/Short radio buttons</h3>
<div class="flex-parent">
<div class="flex-child">
<label><input type="radio" name="gender" value="male" />Male</label>
<label><input type="radio" name="gender" value="female" />Female</label>
</div>
<div class="flex-child">
<label><input type="radio" name="size" value="tall" />Tall</label>
<label><input type="radio" name="size" value="short" />Short</label>
</div>
</div><!-- .flex-parent -->
<div>
<input id="chkType" type="text" value='name="gender"' /><button>Change</button>
</div>