4

我正在使用 jquery 1.2.6(无法升级,因为它是系统的一部分)。我收到一个奇怪的错误。

这是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
    </head>
    <body>
        <select id="state" name="state">
            <option selected="selected"></option>
                        <option value="none">N/A</option>
                        <option value="AK">AK</option>
                        <option value="AL">AL</option>
                        <option value="AR">AR</option>
                        <option value="AZ">AZ</option>
                        <option value="CA">CA</option>
        </select>
    </body>
</html>
<script type="text/javascript">
    $(function() {
        var test = $('#state').val();
    });
</script>

当我在 IE9 中测试时,加载页面时出现此错误:

"Unable to get value of the property 'specified': object is null or undefined" 

这是为什么?

4

2 回答 2

4

The value in an option is optional ("If there isn't, the value of an option element is the textContent of the element."). So you seem to encounter a bug here.

I had a look at the old jQuery source code and I found the bug :

value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;

option.attributes.value is undefined so option.attributes.value.specified crashes.

As the bug is in jQuery (more precisely in what looks like an attempt to work around an old IE bug now fixed), it would be legitimate to not use jQuery on this particular task.

Instead of changing the HTML (your HTML is fine), I recommend to use, as a workaround, the vanilla JS solution :

var test = document.getElementById('state').value;

Note that when I say that the bug is in jQuery, it mainly means the 2008 version of jQuery fails in recent versions of IE while trying to work around bugs of 2008 browsers. You should really tell your architect that keeping this old jQuery isn't a sound decision.

于 2012-12-12T09:22:36.940 回答
2

您选择的选项没有设置值,这就是它抱怨的原因:)

于 2012-12-12T09:18:49.580 回答