加载Javascript选择菜单onchange

时间:2013-03-11 19:11:50

标签: javascript jquery forms firefox selected

我正在使用选择菜单:

<select id="form_frame1" name="frame1" onchange="getChart(this);">
  <option value="area_chart_google" >Area Chart</option>
  <option value="area_chart_2" selected="selected">Stacked Chart</option>
</select>

getChart仅在更改选择时被触发:

function getChart(selection) {
    alert(selection.value);
    //do something
}

问题在于,一旦我加载页面,我就会得到: area_chart_google :这甚至不是之前选择的选择!所以有两件事我不明白:

  1. 为什么加载页面(onload)后会触发onChange事件?
  2. 为什么选择第一个选项,即使以前没有选择过?
  3. 我刚发现这个功能,我猜这就是问题所在:

    jQuery(function() {
     if (localStorage.getItem('form_frame1')) {
        jQuery("#form_frame1 option").eq(localStorage.getItem('form_frame1')).prop('selected', true);
        jQuery("#form_frame1 option").change();
     }
    
     jQuery("#form_frame1").on('change', function() {
        localStorage.setItem('form_frame1', jQuery('option:selected', this).index());
     }); 
    });
    

3 个答案:

答案 0 :(得分:0)

如果您实际使用的是jquery,那么为什么不尝试

$('#form_frame1').change(function(){
   getChart($('#form_frame1').val());
 });

答案 1 :(得分:0)

当您刷新页面时,它会自动选择第一个选项。

答案 2 :(得分:0)

请看这个小提琴。 http://jsfiddle.net/6H9dr/1/

使用如下

$(document).ready(function() {
$('#form_frame1').change(function() {
    alert('Hi');
});

});