javascript onclick提醒不在chrome中工作

时间:2010-12-02 22:32:54

标签: javascript select google-chrome onclick

<select name="history" id="history" >
 <option value="history 1" onClick="alert('h1');">history 1</option>
 <option value="history 2" onClick="alert('h2');">history 2</option>
 <option value="clearhistory" onClick="this.form.submit();" >Clear History</option>
</select>

有人可以帮我这个剧本吗? 我希望每当用户点击历史记录1 ..它将提醒h1 该脚本适用于Firefox和IE,但不适用于Chrome:(

5 个答案:

答案 0 :(得分:12)

如果您想在Chrome,IE等中使用onClick选项元素,则必须使用简短修复:将select元素的onChange属性设置为"this.options[this.selectedIndex].onclick()"

答案 1 :(得分:10)

使用onchange代替onclick选择列表。

<select name="history" id="history" onchange="historyChanged(this);">
 <option value="history1">history 1</option>
 <option value="history2">history 2</option>
 <option value="clearhistory">Clear History</option>
</select>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">

function historyChanged() {
    var historySelectList = $('select#history');
    var selectedValue = $('option:selected', historySelectList).val();

    alert(selectedValue);

    if (selectedValue == 'clearHistory') {
        historySelectList.form.submit();
    }
}

$(function() {
    alert('my alert');
    $('select#history').change(historyChanged);
});

</script>

答案 2 :(得分:7)

在select而不是每个选项上使用onChange。这是jsfiddle http://jsfiddle.net/tBjkg/

<select name="history" id="history" onChange="alert(this.value);">
 <option value="history1">history 1</option>
 <option value="history2">history 2</option>
 <option value="clearhistory">Clear History</option>
</select>

警报(this.value)指的是当前所选的选项中的选项值。

答案 3 :(得分:0)

在某些浏览器中,

第二次选择相同的选项,

没有onchange-event抛出。

这有助于:

<select onchange="alert/*orwhateveryoudowith:*/(this.value);/*but set:*/this.selectedIndex=0">
<option disabled selected>Choose your Plan</option>
<option value=1>Plan 1</option>
<option value=2>Plan 2</option>
<option value=3>Plan 3</option>
</select>

答案 4 :(得分:0)

尽管选定的解决方案有效,但这是一种更清晰,更轻松的方法:

<select name="history" id="history" >
<option value="history 1">history 1</option>
<option value="history 2">history 2</option>
<option value="clearhistory">Clear History</option>
</select>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#history').on('change', function() {
  if ( this.value == 'history 1')
  {
   alert('h1');
  // You can also do anything here
  }
  if ( this.value == 'history 2')
  {
   alert('h2');
  // You can also do anything here
  }
  if ( this.value == 'clearhistory')
  {
   this.form.submit();
  // You can also do anything here
  } 
  });
});
</script>