1

Is this correct or invalid markup (when the option has no value)?
.val()是没有value=""分配时的预期 jQuery 行为吗?

<select id="select_ID">
    <option></option>
    <option>Name</option>
    <option>Recent</option>
</select>

如果我使用$("#select_ID").val();我会得到“名称”/“最近”,但如果选项有一个值,我会得到该值的内容。

我知道.text()在这个例子中会有“名字”和“最近”。只是困惑为什么在没有分配值时.val()给了我。.text()

FIDDLE(注意警报的不同结果)

4

3 回答 3

12

这是正确的 DOM 行为。您可以从此处的 MDN 文档中看到这一点:

价值

如果选择此选项,此属性的内容表示要与表单一起提交的值。如果省略此属性,则该值取自选项元素的文本内容

于 2013-08-13T20:12:23.947 回答
7

这与 jQuery 无关。这就是浏览器处理它的方式。

http://jsfiddle.net/jDw8N/1/

$("#select_ID").change(function () {
    var val = $("#select_ID option:selected")[0].value;
    alert(val); // somevalue or Recent
});

参考:http ://www.w3.org/TR/html5/forms.html#attr-option-value

value属性为元素提供了一个值。元素的值是content属性的值,如果有的话,或者,如果没有,元素的IDL 属性的值。optionvaluetext

于 2013-08-13T20:10:53.607 回答
0

如果您想确保获得value属性的值,可以使用以下代码:

http://jsfiddle.net/sepehrmm/dpmr9h4o/

$("#select_ID").change(function () {
    var val = $("option:selected", this).attr('value');
    if(val != undefined){
        alert(val); // this only alerts if the option has a value attribute
    }
});
于 2016-06-17T13:18:42.783 回答