选择元素不执行onclick for chrome中的选项

时间:2016-02-09 20:30:04

标签: javascript html google-chrome

这是我的代码:

<select style="color:#000000">
<option onclick="window.location.href='/state/FL/1/city/asc'">Sort by City ASC</option>
<option onclick="window.location.href='/state/FL/1/city/desc'">Sort by City DESC</option>
<option onclick="window.location.href='/state/FL/1/name/asc'">Sort by Name ASC</option>
<option onclick="window.location.href='/state/FL/1/name/desc'">Sort by Name DESC</option>
<option onclick="window.location.href='/state/FL/1/dist/asc'">Sort by Distance Nearest</option>
<option onclick="window.location.href='/state/FL/1/dist/desc'">Sort by Distance Furthest</option>

您无法看到结束选择标记,但它在那里。单击选项using chrome but it works for firefox时,它不会更改页面。

不太确定如何解决此问题。

3 个答案:

答案 0 :(得分:2)

选项在某些浏览器中没有鼠标事件,这就是为什么 从不 在选项上使用onclick处理程序的原因,而是{{1}选择上的处理程序。

使用适当的事件处理程序,它将是

onchange

然后在脚本标记中

<select id="mySelect">
    <option value="/state/FL/1/city/asc">Sort by City ASC</option>
    <option value="/state/FL/1/city/desc">Sort by City DESC</option>
    <option value="/state/FL/1/name/asc">Sort by Name ASC</option>
    <option value="/state/FL/1/name/desc">Sort by Name DESC</option>
    <option value="/state/FL/1/dist/asc">Sort by Distance Nearest</option>
    <option value="/state/FL/1/dist/desc">Sort by Distance Furthest</option>
</select>

答案 1 :(得分:1)

选项上的Onclick事件非常不一致,因此您应该在change上设置一个事件,相反,它在浏览器中受支持。此外,应避免使用内联javascript - 因此请选择id并执行以下操作:

<select id="selectId" style="color:#000000">
<option value="/state/FL/1/city/asc">Sort by City ASC</option>
<option value="/state/FL/1/city/desc">Sort by City DESC</option>
<option value="/state/FL/1/name/asc">Sort by Name ASC</option>
<option value="/state/FL/1/name/desc">Sort by Name DESC</option>
<option value="/state/FL/1/dist/asc">Sort by Distance Nearest</option>
<option value="/state/FL/1/dist/desc">Sort by Distance Furthest</option>
</select>

JS:

document.getElementById('selectID').addEventListener('change', e => {
    window.location.href = e.target.value;
});

答案 2 :(得分:0)

jQuery示例:

$('#select').change(function(){
  var currentHref = $(this).find('option:selected').data('href');
  window.location.href = currentHref;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" style="color:#000000">
<option data-href="/state/FL/1/city/asc">Sort by City ASC</option>
<option data-href="/state/FL/1/city/desc">Sort by City DESC</option>
<option data-href="/state/FL/1/name/asc">Sort by Name ASC</option>
<option data-href="/state/FL/1/name/desc">Sort by Name DESC</option>
<option data-href="/state/FL/1/dist/asc">Sort by Distance Nearest</option>
<option data-href="/state/FL/1/dist/desc">Sort by Distance Furthest</option>
</select>