如何使用jquery获取选择标记的属性名称和值

时间:2015-02-05 09:34:43

标签: javascript jquery

我需要使用jquery / javascript获取在select标签中选择的选项的所有属性(带有值的名称)

<select name=student>
    <option id="1" marks="80" gender="f">Abc</option>
    <option id="2" marks="80" gender="m">def</option>
    <option id="3" marks="80" gender="f">xyz</option>
</select>

如何获取所选选项的属性以及属性名称和值id="1",marks="80", gender="f"

1 个答案:

答案 0 :(得分:2)

你可以尝试这样的东西,使用jquery:

// This represents an Attribute.
function Attribute(name, value){
   this.name = name;
   this.value = value;
}

// This is the array of element's attributes
var attributes = [];

$("#elementsId").each(function() {
    $.each(this.attributes, function() {
        if(this.specified) {
            attributes.push(new Attribute(this.name, this.value))
    }
  });
});

在下面的代码段中,我将其应用于第一个选项。

&#13;
&#13;
$(function(){
   
    // This represents an Attribute.
    function Attribute(name, value){
       this.name = name;
       this.value = value;
    }
    
    // This is the array of element's attributes
    var attributes = [];
    
    $("#1").each(function() {
        $.each(this.attributes, function() {
            if(this.specified) {
                attributes.push(new Attribute(this.name, this.value))
        }
      });
    });
  
    for(var i=0; i<attributes.length; i++)
      document.write("name: "+attributes[i].name+" value: "+attributes[i].value+"</br>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name=student>
<option id="1" marks="80" gender="f">Abc</option>
<option id="2" marks="80" gender="m">def</option>
<option id="3" marks="80" gender="f">xyz</option>
</select>
&#13;
&#13;
&#13;