javascript变量的作用域

javascript变量的作用域,javascript,Javascript,我是JavaScript新手,我很难理解一些脚本中变量的范围,这些脚本是我从找到的示例拼凑而成的。下面的代码是在他的网站上发布的教程的一部分。该应用程序有一个ajaxToolKit:ModalPopupXtender,在单击“是”或“否”按钮时可以执行JavaScript函数。应该保存delete按钮位置和div的两个变量似乎没有填充,因此代码异常。当我点击Yes(是)或No(否)按钮时,_Source(源)和_popup(弹出)变量都未定义 我非常感谢花时间来解释我在代码中设置的错误 The

我是JavaScript新手,我很难理解一些脚本中变量的范围,这些脚本是我从找到的示例拼凑而成的。下面的代码是在他的网站上发布的教程的一部分。该应用程序有一个ajaxToolKit:ModalPopupXtender,在单击“是”或“否”按钮时可以执行JavaScript函数。应该保存delete按钮位置和div的两个变量似乎没有填充,因此代码异常。当我点击Yes(是)或No(否)按钮时,_Source(源)和_popup(弹出)变量都未定义

我非常感谢花时间来解释我在代码中设置的错误

The button that is fires the OnClientClick event calling the SubmitPayment function    
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return SubmitPayment(this); return false;" UseSubmitBehavior="False" AccessKey="S" ValidationGroup="Manual" />

A hidden field to save a value in (tested later in the javascript)
    <div id="divHiddenFields">
        <asp:HiddenField ID="hfTotalAmtDue" runat="server" />
    </div>

The Dialog Panel
    <div id="divConfirmPaymentDialog">
        //panel that makes up confirmation dialog
        <asp:Panel ID="pnlConfirmPaymentDialog" runat="server" style="display:none" CssClass="modalPopup" Height="200" Width="450">
            <div align="center">
                <p class="info">You are attempting to make a payment when your account(s) has/have no balance!</p>
                <p class="info">If you do this you will have a credit applied to your account in the amount of your payment.</p>
                <p class="info">Are you sure that you want to do this?</p>
                <asp:Button ID="btnConfirmPaymentYes" runat="server" Text="Yes" Width="75" />
                <asp:Button ID="btnConfirmPaymentNo" runat="server" Text="No" Width="75" />
            </div>
        </asp:Panel>
        //modal dialog extender that implements showing the modal dialog with panel
        <cc1:ModalPopupExtender ID="mpeConfirmPayment" runat="server" BehaviorID="mpeConfirmPaymentBehaviorID" BackgroundCssClass="modalBackground" 
        CancelControlID="btnConfirmPaymentNo"  OnCancelScript="btnConfirmPaymentNo_Click();" OkControlID="btnConfirmPaymentYes" OnOkScript="btnConfirmPaymentYes_Click();" 
        PopupControlID="pnlConfirmPaymentDialog" TargetControlID="pnlConfirmPaymentDialog" />
    </div>   

The Javascript
    <script type="text/javascript">       
        //this system function sets the App_init handler function as the initialization handler
        Sys.Application.add_init(App_Init);
        //this function handles the hookup of the beginrequest and endrequest ="divhandlers.  The two functions are called
        //at the begin and end of the webpage lifecycle
        function App_Init()
        {
          Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
          Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
        }
        //this function handles the begining of the webpage lifecylce
        function BeginRequest(sender, args){
            $(document).ready(function(){
                //if btnYes was clicked then block the UI
                $('#<%= btnYes.ClientID %>').live('click', function(e){
                    //e.preventDefault();
                    $.blockUI();
                });
            });
        }
        //this function handles the end of the webpage lifecylce
        function EndRequest(sender, args) {
            //call unblockUI 
            $(document).ready(function() {
                $('#<%= btnYes.ClientID %>').live('click', function(e) {
                    $.unblockUI();
                });
            });

            //check for errors that occurred during page execution
            if (args.get_error() != undefined) {
                var errorMessage;
                if (args.get_response().get_statusCode() == '200') {
                    errorMessage = args.get_error().message;
                }
                else {
                    // Error occurred somewhere other than the server page.
                    errorMessage = 'An unspecified error occurred. ';
                }
                args.set_errorHandled(true);
                if (errorMessage.indexOf('ValidationError:') > 0) {
                    alert(errorMessage.replace('Sys.WebForms.PageRequestManager', '').replace('ServerErrorException:', ''));
                }
            }
        }
        //this funcion will raise the viewccreceipt dialog when called
        function OpenReceipt() {
            window.open('ViewCCReceipt.aspx', 'Name', 'height=600,width=800');
        }

        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;

        //This function will be called when the submit button on the creditcard entry screen is pressed.
        //The function will check to see if the balance is already zero and message the customer that they will have a
        //credit balance if they continue and allow the to confirm the payment.
        function SubmitPayment(source) {
            $(document).ready(function() {
                //Get the Total Amount Due from hidden field hfTotalAmountDue
                var TotalAmtDue = $('#<%= hfTotalAmtDue.ClientID %>').val();
                if (TotalAmtDue <= 0) {
                    this._source = source;
                    this._popup = $find('mpeConfirmPaymentBehaviorID');
                    //  find the confirm ModalPopup and show it    
                    this._popup.show();
                }
            });
        }
        //event handler for the btnConfirmPaymentYes button
        //when this handler is executed the modal popup is hidden and a postback is done
        function btnConfirmPaymentYes_Click(){
            //  find the confirm ModalPopup and hide it    
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, '');
        }
        //event handler for the btnConfirmPaymentNo button
        //when this handler is executed the modal popup is hidden and the postback permanently shut down
        function btnConfirmPaymentNo_Click(){
            //  find the confirm ModalPopup and hide it 
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>
用于触发调用SubmitPayment函数的OnClientClick事件的按钮
保存值的隐藏字段(稍后在javascript中测试)
对话框面板
//组成确认对话框的面板

当您的帐户有/没有余额时,您正试图付款

如果您这样做,您将在您的帐户上获得一笔金额为您的付款的信用

您确定要这样做吗

//模式对话框扩展器,实现用面板显示模式对话框 Javascript //此系统函数将App_init handler函数设置为初始化处理程序 Sys.Application.add_init(App_init); //此函数处理beginrequest和endrequest=“divhandlers”的连接。这两个函数被调用 //在网页生命周期的开始和结束时 函数App_Init() { Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest); } //此函数用于处理网页生命周期的开始 函数BeginRequest(发送方,参数){ $(文档).ready(函数(){ //如果单击了btnYes,则阻止UI $('#').live('单击'),函数(e){ //e、 预防默认值(); $.blockUI(); }); }); } //此函数用于处理网页生命周期的结束 函数EndRequest(发送方,参数){ //调用unbui $(文档).ready(函数(){ $('#').live('单击'),函数(e){ $.unbui(); }); }); //检查页面执行期间发生的错误 if(args.get_error()!=未定义){ var错误消息; if(args.get_response().get_statusCode()=='200'){ errorMessage=args.get_error().message; } 否则{ //在服务器页面以外的其他位置发生错误。 errorMessage='发生了未指定的错误'; } args.set_errorHandled(true); if(errorMessage.indexOf('ValidationError:')>0){ 警报(errorMessage.replace('Sys.WebForms.PageRequestManager','')。replace('ServerErrorException:',''); } } } //调用此函数时,将引发ViewCCReceive对话框 函数OpenReceipt(){ window.open('viewcreceipt.aspx','Name','height=600,width=800'); } //跟踪行的“删除”按钮 //这将被删除 var_源; //跟踪弹出的div var_弹出窗口; //当按下信用卡输入屏幕上的提交按钮时,将调用此功能。 //该功能将检查余额是否已为零,并向客户发送信息,告知他们将有一个 //信用余额,如果他们继续,并允许客户确认付款。 功能提交支付(来源){ $(文档).ready(函数(){ //从隐藏字段hfTotalAmountDue获取到期总金额 var TotalAmtDue=$('#').val();
if(TotalAmtDue
此._source
与JavaScript中的
var _source
不同

而不是做

this._source = source;
this._popup = $find('mpeConfirmPaymentBehaviorID');
也许你应该这样做

_source = source;
_popup = $find('mpeConfirmPaymentBehaviorID');
它将(在文档加载时)分配给包含事件处理程序函数定义的作用域中声明的变量:
btnConfirmPayment{No,Yes}\u单击


很多时候这两者是等价的,因为默认情况下,
这个
引用全局范围,并且您的
var
声明在全局范围内,但是加载事件处理程序可能是在
这个
是某个DOM节点的情况下运行的。

范围是一件棘手的事情,下面是一些基础知识

唯一的作用域是函数作用域。函数中声明的变量保留在函数中。函数外部声明的变量位于全局作用域中。但要避免使用全局变量,因为它们的样式不好

函数是没有主的对象。在两种情况下,只能依赖
this
的值:

  • 您这样调用函数:
    functionname.call(context,params)
    ,其中context是
    this
  • 您的函数是另一个对象的一部分。
    将是它所属的对象
    • 注意:如果该功能与该功能分离,则所有下注都将关闭
如果以这种方式调用函数:
functionname(params)
,那么
这个
将是调用范围中的任何内容。这有点奇怪,所以如果要使用它,请确保您知道它是什么