在选择框中单击已选择的选项 [英] Click already selected option in select box

查看:62
本文介绍了在选择框中单击已选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎应该很容易,但是< select> 对象的局限性令人不快。我有一个带有四个选项的选择框,当您导航到页面时,该选项将设置为您所在的页面。我要这样做,以便用户可以通过选择相同的选项(即选择已选择的选项)来刷新页面。

This seems like it should be easy, but the limitations of the <select> object are rather irritating. I have a select box with four options, and when you navigate to a page, the option is set to the page you are on. I want to make it so that the user can refresh the page by selecting the same option - that is, selecting the option that's already selected.

不幸的是, onclick 事件不适用于所有浏览器。大多数人建议使用 onchange ,但这在我所说的情况下不起作用。我一直采用的方法是在顶部添加一个额外的项目,该项目保留当前选择的内容,并且在单击时不执行任何操作,然后在触发onchange事件后切换到该选项,以便当用户重新选择该选项时他们实际上正在改变。不过这很尴尬,因为在下拉列表中有两个相同的项目,我不必这样做。

Unfortunately, the onclick event doesn't work across browsers. Most people recommend using onchange, but that doesn't work in the case I'm talking about. The approach I've been taking is to add an extra item at the top that holds what's currently selected and does nothing when clicked on, and then switch to that option after firing the onchange event, so that when the user re-selects the option they're actually changing. That's awkward though, because in the drop-down there are two of the same item, and I shouldn't have to do it.

什么是一个好的跨浏览器解决这个问题的方法?

What is a good cross-browser way to solve this problem? Something not terribly complicated and something in regular JavaScript would be preferable.

推荐答案

这可能会帮助:

function onFocus(element){
    element.setAttribute('old-value',element.value);
    element.value='';
    console.log('reset');
}

function onBlur(element){
    if(element.value=='')
        element.value = element.getAttribute('old-value');
    element.removeAttribute('old-value');   
}

function onChange(element){
    console.log('New Value : '+ element.value);
}

<select id="mySelect"  onfocus="onFocus(this)" onchange="onChange(this)" onblur="onBlur(this);">
    <option value="" style="display:none;"></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
</select>

这篇关于在选择框中单击已选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆