【问题标题】:ASP.NET onClientClick return false not workingASP.NET onClientClick 返回 false 不起作用
【发布时间】:2019-04-28 00:12:51
【问题描述】:

我想在单击按钮时隐藏 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>

【问题讨论】:

    标签: javascript asp.net autopostback


    【解决方案1】:

    添加 onclientclick 按钮:

    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>
    

    【讨论】:

    • 非常感谢您的帮助我能够解决它我不知道CollapseButton有一个属性OnClientClick。
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2016-05-18
    • 2021-09-05
    • 2015-07-13
    • 2018-12-05
    • 1970-01-01
    • 2011-10-12
    • 2021-12-10
    相关资源
    最近更新 更多