javascript - 当没有设置 value 属性时,val() 返回 html() 而不是 <option> 标签的 undefined

标签 javascript jquery

考虑以下 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/

相关文章:

javascript - 如何更新模态主体并通过链接单击打开

javascript - 使用 jQuery attr 方法

c# - 在 VS2010 的 asp.net mvc 4 中使用 jqueryUI 打开模式窗口

javascript - 当页面刷新时,AngularJS 到底会发生什么?

javascript - 如何使 create-react-app 自动构建?

javascript - 如何在我的 jquery 菜单中的 li 项下添加一行?

javascript - 随着用户向下滚动逐渐改变导航背景

javascript - react-native - 图片需要来自 JSON 的本地路径

javascript - ng.probe(selector) 总是导致 NULL

jquery - 使用 jQuery 操作 td