1. 程式人生 > >Javascript 回撥函式

Javascript 回撥函式

1 在檢視或html頁面中輸入如下指令碼

<script type="text/javascript">
    function openClient(arg) {
        try {
            var wsh = new ActiveXObject("UstcOriWebLabActivex.UstcOriWebLab");
            window.open(arg);
        }
        catch (e) {
            alert("error");
            window.open("/Download.html");
        }
    }

2 函式需要回調openClient

function payOrder(url, callback) {
        if (this.loadWaiting != false) {
            return;
        }
        this.setLoadWaiting(true);
        $.ajax({
            cache: false,
            url: url,
            type: 'post',
            success: function (response) {
                if (response.isloing) {
                    callback(response.arg);
                }

                location.href = response.url;
            },
            complete: this.resetLoadWaiting,
            error: this.ajaxFailure
        });
    }

3 呼叫payOrder

<div class="product-item" data-productid="@Model.Id">

    <div class="picture">
        <a href="@Url.RouteUrl("Product", new { SeName = Model.SeName })" title="@Model.DefaultPictureModel.Title">
            <img alt="@Model.DefaultPictureModel.AlternateText" src="@Model.DefaultPictureModel.ImageUrl" title="@Model.DefaultPictureModel.Title" />
        </a>
    </div>
    <div class="details">
        <h2 class="product-title">
            <a href="@Url.RouteUrl("Product", new { SeName = Model.SeName })">@Model.Name</a>
        </h2>
        <div class="description">

            @Html.Raw(Model.ShortDescription)
        </div>
        <div class="add-info">
            <div class="prices">
                @if (!String.IsNullOrEmpty(Model.ProductPrice.OldPrice))
                {
                    <span class="price old-price">@Model.ProductPrice.OldPrice</span>
                }
                <span class="price actual-price">@Model.ProductPrice.Price</span>
            </div>
            <div class="buttons">
                @if (!Model.ProductPrice.DisableBuyButton)
                {                    
                    <input type="button" value="@T("ShoppingCart")" class="button-2 product-button"   onclick="AjaxCart.payOrder('@addtocartlink', openClient)" />
               }
            </div>
            @Html.Widget("productbox_add_info")
        </div>

    </div>
</div>

4  總結
注意:在payOrder中callback()是需要“()”,要不回撥會不成功!

結論:CallBack函式其實只是一個函式形參
意思是需要傳一個函式物件給他,你自定義的payOrder本身就是一個函式物件,直接傳進去就行了,不需要加上‘’,否則就變成一個字串物件了