如何获取当前所选SELECT的参数?

时间:2012-01-25 01:24:32

标签: javascript jquery html

<select id="sel">
    <option value="1" test="aaa">dsfsdf</option>
    <option value="2" test="bbb">ssssss</option>
    <option value="3" test="ccc">dggggg</option>
</select>

<span id="check">check</span>

$("#check").click(function(){

console.log($("#sel option").attr("selected", true).attr('test'));
})

现场:http://jsfiddle.net/rhqbG/

现在这告诉我总是“aaa”。我该怎么做?

3 个答案:

答案 0 :(得分:4)

您可以将其重写为

console.log($("#sel option:selected").attr('test'));

http://jsfiddle.net/gYpYV/

答案 1 :(得分:1)

document.getElementById('sel').value;

应该做的伎俩。

修改

var sel = document.getElementById('sel');
var opt = sel.options[sel.selectedIndex];
// now get attributes of opt, such as:
console.log(opt.getAttribute("test"));

答案 2 :(得分:1)

请注意,在元素上包含不符合自定义的属性是不好的做法。如果您使用的是HTML 5,则可以使用“data-”自定义属性,但是最好保持与该元素关联的值的JavaScript哈希值。