我想在按钮单击时隐藏div并在不同的按钮单击上显示它们。遗憾的是,图像按钮单击总是有回发。是什么导致了这个问题?
这是我的后端代码
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 10; i++)
{
HtmlGenericControl divTest = new HtmlGenericControl("div");
divTest.Attributes.Add("class", "divClass");
divTest.Attributes.Add("ID", "myDIV");
divTest.InnerText = "Div" + i;
form1.Controls.Add(divTest);
ImageButton collapseButton = new ImageButton();
collapseButton.ImageUrl = "~/images/minus.png";
collapseButton.Attributes.Add("OnClientClick", "myHideFunction(); return false;");
collapseButton.Height = 20;
collapseButton.Width = 20;
divTest.Controls.Add(collapseButton);
ImageButton expandButton = new ImageButton();
expandButton.ImageUrl = "~/images/plus.png";
collapseButton.Attributes.Add("OnClientClick", "myShowFunction(); return false;");
expandButton.Height = 20;
expandButton.Width = 20;
form1.Controls.Add(expandButton);
}
}
这是我的前端代码
CSS
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
使用Javascript
<script>
function myShowFunction() {
var x = document.getElementById("myDIV");
x.style.display = "block";
}
function myHideFunction() {
var x = document.getElementById("myDIV");
x.style.display = "none";
}
</script>
添加onclientclick on按钮:
collapseButton.OnClientClick = "return myHideFunction();");
你需要从你的方法中返回false,如下所示:
<script>
function myShowFunction() {
var x = document.getElementById("myDIV");
x.style.display = "block";
return false;
}
function myHideFunction() {
var x = document.getElementById("myDIV");
x.style.display = "none";
return false;
}
</script>