我这里有两组单选按钮,我想在动态选择时获取Name和Value属性的内容。我确实得到了value属性的内容,但没有得到name属性。 感谢您的帮助! 这是代码:
var var1 = "";
function myFun(){
$( "input[type=radio]:checked" ).each(function(){
var1 = $(this).val();
alert(var1);
});
}

<form>
<h3>Fruits</h3>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<h3>Delivery</h3>
<div>
<input type="radio" name="delivery" value="Y" id="y">
<label for="orange">Yes</label>
</div>
<div>
<input type="radio" name="delivery" value="N" id="n">
<label for="apple">No</label>
</div>
<button onclick="myFun()">Submit</button>
</form>
&#13;
答案 0 :(得分:3)
您可以使用this.name
获取name属性:
var var1 = "";
function myFun() {
$("input[type=radio]:checked").each(function () {
var1 = $(this).val();
var2 = this.name;
console.log(var1,var2);
});
}
<强> jsFiddle example 强>
答案 1 :(得分:2)
$(this).attr("name")
答案 2 :(得分:2)
试试这个:
var var1 = "";
function myFun(){
$( "input[type=radio]:checked" ).each(function(){
var1 = $(this).val();
var2 = $(this).attr("name");
alert(var1);
alert(var2);
});
}
<form>
<h3>Fruits</h3>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<h3>Delivery</h3>
<div>
<input type="radio" name="delivery" value="Y" id="y">
<label for="orange">Yes</label>
</div>
<div>
<input type="radio" name="delivery" value="N" id="n">
<label for="apple">No</label>
</div>
<button onclick="myFun()">Submit</button>
</form>
答案 3 :(得分:-1)
当您想要在用户选中或取消选中单选按钮后触发时,您也可以在更改事件上执行此操作 您可以使用jquery .attr函数获取名称attr:
$('input[type=radio]').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
});
您还可以通过
检查单选按钮是否已选中if($(this).is(':checked')){
console.log('is_checked');
}