use*_*312 2 variables jquery static
请指导我在以下程序中声明静态变量.我想通过单击按钮增加静态变量lists.counter的值.但它不起作用.
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="finalspecific2_list._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function lists() {
var list = $('#myList li:gt(0)');
list.hide();
lists.counter = 0;
var username = $("#<%= uname.ClientID %>").val();
var pwd = $("#<%= pwd.ClientID %>").val();
$("#<%= Login.ClientID %>").click(function () {
lists.counter++;
alert(lists.counter);
lists.counter++;
});
$("#<%= Button1.ClientID %>").click(function () {
{
alert(lists.counter);
}
});
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Button ID="Login" runat="server" Text="Login" />
<asp:Button ID="Button1" runat="server" Text="Login" />
</ul>
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
如果单击任何按钮,lists.counter应该增加,并且应该随后的点击增加.请指导此事.
你可以在这里使用一个闭包:
$(document).ready(function() {
// The actual counter is contained in the counter closure.
// You can create new independent counters by simply assigning
// the function to a new variable
function makeCounter() {
var count = 0;
return function() {
count++;
return count;
};
};
// This variable contains a counter instance
// The counter is shared among all calls regardless of the caller
var counter = makeCounter();
// The handler is bound to multiple buttons separated by commas
$("#button, #another_button, #yet_another_button").click(function () {
var i = counter();
console.log("The counter now is at " + i);
// Probably update your counter element
// $("#counter").text(i);
});
});?
Run Code Online (Sandbox Code Playgroud)
你可以在这个小提琴中找到代码.
如果您有兴趣,可以在这里阅读更多关于闭包的内容.
更新: 这个小提琴使用共享同一个计数器的多个按钮.
| 归档时间: |
|
| 查看次数: |
21992 次 |
| 最近记录: |