我正在尝试根据所选下拉值显示/隐藏我网页中的链接。
这是我的下拉菜单和链接
<asp:DropDownList ID="ddlOption" runat="server" Width="100px" onchange="templateVisbility()">
<asp:ListItem Value="Value1" Text="Value1" Selected="True"> </asp:ListItem>
<asp:ListItem Value="Value2" Text="Value2"> </asp:ListItem>
</asp:DropDownList>
<asp:HyperLink ID="Link1" runat="server" NavigateUrl="/myexcel.xlsx" Text="test template" />
JavaScript
隐藏/显示链接
<script type="text/javascript">
function templateVisbility() {
var e = document.getElementById("ddlOption");
var selectedval = e.options[e.selectedIndex].value;
if (selectedval != 'Value1') {
document.getElementById('Link1').style.visibility = 'hidden';
}
else {
document.getElementById('Link1').style.visibility = 'visible';
}
}
</script>
它按预期工作,但我觉得我做了太多简单的工作。有没有更好/更简单的方法来做到这一点。
答案 0 :(得分:2)
你无能为力。您可以将this
传递给函数以减少一行:
function templateVisbility(thatObj) {
var selectedval = thatObj.options[thatObj.selectedIndex].value;
if (selectedval != 'Value1') {
document.getElementById('Link1').style.visibility = 'hidden';
}
else {
document.getElementById('Link1').style.visibility = 'visible';
}
}
<select id="ddlOption" onchange="templateVisbility(this)">
<option value="Value1">Value1</option>
<option value="Value2">Value2</option>
</select>
<a href="#" id="Link1">Link1</a>
<a href="#" id="Link2">Link2</a>