Javascript 下拉菜单中的 OnClick() 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3700375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OnClick() event in dropdown
提问by Rene Zammit
I have a dropdown menu. When I click on "Italian" in the dropdown, I want the content for Italian to show. Basically, what I want is to set the action to IT when I select Italian from the dropdown. How might I apprach this?
我有一个下拉菜单。当我点击下拉菜单中的“意大利语”时,我希望显示意大利语的内容。基本上,当我从下拉列表中选择意大利语时,我想要的是将操作设置为 IT。我该如何处理?
<% action = Request.QueryString("action") %>
<form name="contentchanger" action="/" method="post">
<select name="flag" name="flag">
<option value="Choose" selected="selected">Choose</option>
<option value="italian" onclick="what code i should use here?">Italian</option>
</select>
</form>
<a href="?action=FR">FR</a>
<a href="?action=IT">IT</a>
<%
if action = "IT" Then
Response.Write("<p>This is italian</p>")
else if action = "FR" Then
Response.Write("<p>This is French</p>")
end if
end if
%>
回答by Mark Baijens
It is better to use onchange event on the select box. Onclick doesn't work well in all browsers. Bind a javascript function to the onchange event that changes the url of the a element (or redirect to the correct url if you want to change it instantly).
最好在选择框上使用 onchange 事件。Onclick 并非在所有浏览器中都能正常工作。将 javascript 函数绑定到更改 a 元素的 url 的 onchange 事件(或者如果您想立即更改它,则重定向到正确的 url)。
Something like this should work. I recomment using a javascript libary like jquery if you want to do more interactive client side functionality
像这样的事情应该有效。如果您想做更多交互式客户端功能,我建议使用像 jquery 这样的 javascript 库
changeLanguage()
改变语言()
<select onchange="changeLanguage(this.value)">
<option value="Choose" selected="selected">Choose</option>
<option value="IT" >Italian</option>
<option value="FR" >France</option>
</select>
<a id="url" href="?action=IT">IT</a>
Javascript:
Javascript:
function changeLanguage(language) {
var element = document.getElementById("url");
element.value = language;
element.innerHTML = language;
}
Update:
更新:
Code I used for my test. This works in the most recent versions of chrome, firefox and ie.
我用于测试的代码。这适用于最新版本的 chrome、firefox 和 ie。
<html>
<head>
<script>
function changeLanguage(language) {
var element = document.getElementById("url");
element.value = language;
element.innerHTML = language;
}
</script>
</head>
<body>
<select onchange="changeLanguage(this.value)">
<option value="Choose" selected="selected">Choose</option>
<option value="IT" >Italian</option>
<option value="FR" >France</option>
</select>
<a id="url" href="?action=IT">IT</a>
</body>
</html>

