简体   繁体   中英

jQuery and ASP.NET Page load

I test jQuery and ASP.NET with Webcontrols and in my test load the Side everytime new if I click on the Button. The jQuery Code add a Css Class to a Label.

My aspx:

      <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="jQueryAnwendung.Main" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <script src="Scripte/jquery-1.8.0.min.js" type="text/javascript"></script>

    <style type="text/css">
        .CssKlasse 
        {
            background:red;
            font-size:40px; 
            }
    </style>

    <script type="text/javascript" language="javascript">

        $(document).ready(function () {
            $("#<%= b1.ClientID%>").click(function (event) {
                $("#<%= bild1.ClientID %>").slideToggle('slow');
            });

        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="b1" runat="server" text="Bild verkleinern/vergrößern"/>
        <asp:Image ID="bild1" runat="server" ImageUrl="~/Theme/net.png" Width="50" Height="50" /> 
    </div>
    </form>
</body>
</html>

What can I do?

tarasov

The generated id is more verbose; open your browser and click View source . You will notice it. Copy and paste the ID into your jQuery selector.

Another way is to call b1.clientID inside your .aspx : $("<%= b1.ClientID %>") , which will output the generated clientID at runtime.

Since ASP.NET 4, StaticMode allows you to have complete control over the generated ID. For more information, check it out: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx

if you using asp controls you have 2 ways to handle it

First is change "#b1 and "#l1" to "<%= #b1.ClientID%>" and "<%= #l1.ClientID %>" in your jQuery function

Second is to add attribute ClientIDMode="Static" to your asp:Button and asp:Label

单击它时Asp按钮会导致Post返回 - 页面重新加载并且您的脚本未执行,您可以使用HTML按钮或尝试禁用此按钮上的回发。

inside your handler, prevent the button from behaving normally:

$("#<%= b1.ClientID%>").click(function (event) {
  event.preventDefault(); //prevent the control to act in its default way
  $("#<%= bild1.ClientID %>").slideToggle('slow');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM