【问题标题】:Visual studio 2012- using javascript functionVisual Studio 2012-使用javascript函数
【发布时间】:2015-03-22 11:45:19
【问题描述】:

我尝试从 javascript 函数更改背景。颜色改变但立即恢复到原来的颜色。 我做错了什么? 谢谢

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">
    <title></title>

    <script type="text/javascript">
        function acheck() {
            document.body.style.backgroundColor = "yellow";

        }
    </script> </head>

<body>
    <form id="form1" runat="server">
    <div><p id="p2" >
        <script>  document.body.style.backgroundColor = "blue";

        </script>

         </p>

     <asp:Button ID="Button1" runat="server" OnClientClick="acheck()" Text="Button" />


    </div>

    </form> </body> </html>

【问题讨论】:

  • 您的 acheck 函数中缺少右括号 }

标签: javascript html asp.net visual-studio-2012


【解决方案1】:

更改您的功能以防止默认行为 - 它将发布表单并重新加载页面。

<script type="text/javascript">
    function acheck(e) 
    {
        document.body.style.backgroundColor = "yellow";
        e.preventDefault();
    } // this bracket also missing in your code
</script>

其他选项有:

e.stopPropagation();
e.stopImmediatePropagation();
return false;

都有不同的目的和结果。

文档地址:https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

【讨论】:

  • 你能把生成的HTML和脚本贴出来吗?
  • 这是所有代码。我尝试了一个最小的文件来发现错误。我从来没有用过e。防止违约。我必须在主代码中添加更多代码,还是在其他地方添加更多代码?
【解决方案2】:

嘿,我希望你已经在服务代码中编写了一个事件......如果不只是从你的按钮中删除 run at server 属性......

我认为您正在通过 run at server 按钮的属性调用一些服务器事件。那是发回帖子,这会导致页面重新加载,从而使您的页面变为旧颜色...

为避免回发页面刷新,您必须在服务器中处理好它,或者只是从您的按钮中删除此在服务器上运行的属性(这将导致您的脚本没有服务器调用)..

我希望这可以解决您的问题或帮助您了解问题。

(抱歉打错字。从移动应用发送)。

【讨论】:

    【解决方案3】:

    谢谢 我找到了一个简单的解决方案:

    <asp:Button ID="Button1" runat="server" OnClientClick="acheck();return false;" Text="Button" />
    

    【讨论】:

      猜你喜欢
      • 2013-09-08
      • 1970-01-01
      • 2012-10-23
      • 2015-01-02
      • 1970-01-01
      • 2012-10-11
      • 2012-07-14
      • 2017-11-07
      • 2014-11-20
      相关资源
      最近更新 更多