如何使用jquery从元素中获取属性?

时间:2013-08-14 02:58:51

标签: javascript jquery json checkbox key-value

这是我的example

<fieldset data-role="controlgroup" id="test">
    <legend>Radio buttons, vertical controlgroup:</legend>
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked">
    <label for="radio-choice-1">Cat</label>
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2">
    <label for="radio-choice-2">Dog</label>
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3">
    <label for="radio-choice-3">Hamster</label>
    <input class="status" type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4">
    <label for="radio-choice-4">Lizard</label>
</fieldset>

$('.status').on("click", function () {
    var inputs = $('#test').find('input');
    $.each(inputs, function (i, v) {
        console.log(v);
    });
});

我想获得所有单选按钮的idval(),例如:

[{
    id: id1,
    value: value1
} {
    id: id2,
    value: value2
}]
...

任何想法?

2 个答案:

答案 0 :(得分:1)

要获取元素的属性,您可以使用.attr()之类的Fiddle

但要在上述情况下获得所需的输出,您可以使用

$(el).attr('class')

演示:{{3}}

答案 1 :(得分:1)

$('.status').on("click", function () {

var radioid = $(this).attr('id'); //gets the attribute ID of the clicked `.status`
    radioval = $(this).val(); //gets the value of of the clicked `.status`
alert('ID = ' + radioid + ' and VALUE = ' + radioval); //see the magic


var inputs = $('#test').find('input');
$.each(inputs, function (i, v) {
    console.log(v);
});

});

使用jquery attr()获取属性ID(和其他属性)和val()以获取单选按钮的值

DEMO

相关问题