Home >Web Front-end >HTML Tutorial >Perfectly solves the problem that the select option in HTML cannot be hidden.
I encountered this problem accidentally during the development process, and the first time to solve the problem was Baidu. The results are as follows:
1. The solution of setting display:none of option first is definitely not feasible;
2. Two solutions proposed by a netizen:
a. On the option tag Adding the disabled="disabled" attribute indicates that it is unavailable. This solution only makes the option unselectable, but does not hide it
b. If you want to hide it, you can only remove the option from the DOM tree, and then modify the removed option The option is cached, and then the option is taken out of the cache and added to the DOM tree when it is to be displayed.
It is definitely not in line with the requirements.
c. The ultimate solution (tested to be compatible with all browsers): Add a parent tag to the option, and set the parent tag to hide [the span tag is used here]. If you want to display it, remove the parent tag. Can.
However, the above methods are of no use
Final solution:
//将select通过clone方法保存 var select= $("#select").clone(); //删除所有的option $("#select").find('option').remove(); //查找出需要显示的option并复制 var options = select.find("option[value=1]").clone(); //将需要显示的option添加到select中 $("#select").append(options); //因为option.remove()不会刷新控件,需要将新的option切换上去 //这里排除了options.size() == 0的情况 $("#select").find('option').eq(0).attr("selected",true);
That’s it.
More perfect solutions to the problem that the select option in HTML cannot be hidden. For related articles, please pay attention to the PHP Chinese website!