【问题标题】:how to get an attribute from an element with jquery?如何使用 jquery 从元素中获取属性?
【发布时间】:2013-08-14 11:17:57
【问题描述】:

这是我的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
}]
...

有什么想法吗?

【问题讨论】:

    标签: javascript jquery json checkbox key-value


    【解决方案1】:

    要获取元素的属性,您可以使用.attr(),例如$(el).attr('class')

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

    $('.status').on("click", function () {
        var array = $('#test').find('input').map(function(idx, el){
            return {id: el.id, value: el.value}
        }).get();
        console.log(JSON.stringify(array));
    });
    

    演示:Fiddle

    【讨论】:

      【解决方案2】:
      $('.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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-09
        • 2011-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-16
        • 1970-01-01
        相关资源
        最近更新 更多