考虑以下 HTML:
<select>
<option value="hasAttr">Has a value attr</option>
<option>Does not have a value attr</option>
</select>
如您所见,其中一个选项设置了值属性,而另一个则没有。但是,当我去检查 val()
对于通过 jQuery 的每个选项,没有设置 value 属性的选项返回标签内的文本 ( html()
) 而不是 undefined
正如我通常所期望的那样。
var $select = $('select');
$select.each(function() {
var $this = $(this),
$options = $this.children('option');
$options.each(function(){
var $option = $(this),
$value = $option.val(),
$html = $option.html();
console.log('Option Value: '+ $value +'\nOption HTML: '+ $html);
});
});
即使我更改代码以查找 $option.attr('value')
,我仍然得到相同的结果。有没有一种方法可以检查是否有 <option>
有一个 value
是否存在将返回 bool 值的属性?
这是一个jsFiddle .
已更新 jsFiddle与解决方案。
最佳答案
这是正确的标准行为。在没有 value
属性的情况下,元素的文本内容用作元素的值。
来自W3C website :
If there isn't [a value attribute], the value of an option element is the textContent of the element.
您可以在 DOM 节点上使用 getAttribute
测试内容属性是否存在:
$option[0].getAtribute('value') // returns null
或者,您可以使用带有“has-attribute”选择器的 jQuery is
方法:
$option.is('[value]') // returns false
关于javascript - 当没有设置 value 属性时,val() 返回 html() 而不是 <option> 标签的 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499241/