繁体   English   中英

selectedIndex-Google Chrome上的javascript

[英]selectedIndex - javascript on Google Chrome

谁能告诉我为什么在Google Chrome浏览器上无法正常工作:

val = document.form.option[document.form.selectedIndex].value;

我应该如何解决这个问题,以免其他浏览器(例如IE和FF)搞砸了。
提前谢谢了。

尝试这个:

<select id="option">
....
</select>

然后

val = $('#option').val();

这是因为您实际上没有选择表单元素。 它应该是这样的(我假装您的选择名为myselect ):

var formElement=document.getElementsByName("myselect")[0]; /* Select the form element */
var val=formElement.options[formElement.selectedIndex].value; /* Grab its value */

这是一个实际的例子

从jQuery的页面

$('select.foo')。val(); //从下拉列表中获取值选择更加容易

元素为select时函数val jQuery(1.4.2)代码

if ( jQuery.nodeName( elem, "select" ) ) {
    var index = elem.selectedIndex,
        values = [],
        options = elem.options,
        one = elem.type === "select-one";

    // Nothing was selected
    if ( index < 0 ) {
        return null;
    }

    // Loop through all the selected options
    for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
        var option = options[ i ];

        if ( option.selected ) {
            // Get the specifc value for the option
            value = jQuery(option).val();

            // We don't need an array for one selects
            if ( one ) {
                return value;
            }

            // Multi-Selects return an array
            values.push( value );
        }
    }

    return values;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM