我可以继续使用之前的防止链接吗?

时间:2013-09-20 08:33:45

标签: javascript jquery .net

我有这个链接:

$('.popup-window').click(function (e) {
    e.preventDefault();

    $.ajax({
        ...
    })
});

这是一个.NET LinkBut​​ton(一个调用javascript而不是真正的href的链接)。如果ajax返回一些(假设,假),我想阻止Default。否则,如果为true,则继续使用该链接处理程序。

我该怎么做?

P.S。我在开始时需要e.preventDefault();,否则.NET处理程序将立即采取行动。

3 个答案:

答案 0 :(得分:1)

我想我明白你在寻找什么。

这是我的想法:在DOM元素上使用data属性来决定是否应该阻止默认事件。最初,事件被阻止,但ajax有权“解锁”?它,然后再次开火。这是一些定制工作,但它可以做到这一点:

var $popupWindow=$('popup-window');

// initially "tell" the LinkButton to prevent default
$popupWindow.data('prevent-default', 1);

// the click event (initially prevents default)
$popupWindow.click(function(e){
    var $this=$(this);

    if ($this.data('prevent-default')==0) { // if "unlocked"

        // "lock" it again (default isn't prevented)
        $this.data('prevent-default', 1);

    } else { // if "locked"
        // default is prevented
        e.preventDefault();

        // test if it should be unlocked
        $.ajax({
            // ...
        }).done(function(data){
            if (data.length>0 && data.response==false) {
                // set the attribute so it shouldn't prevent default
                $this.data('prevent-default', 0);

                // trigger this click (should let the event fire completely)
                $this.trigger('click');
            }
        });
    }
});

<强>更新

另一种方法是添加页面方法。

(参见:Using jQuery to directly call ASP.NET AJAX page methods

这会将机制减少到这样的思考:

$('popup-window').click(function(e){
    e.preventDefault();

    $.ajax({
        // ...
    }).done(function(data){
        if (data.length>0 && data.response==false) {
            $.ajax({
                type: "POST",
                url: "YourPage.aspx/YourMethod",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    // Replace the div's content with the page method's return.
                    $("#Result").text(msg.d);
                }
            });
         }
     });
});

答案 1 :(得分:1)

您可以使用__doPostBack() js函数触发AJAX回调中的回发。

唯一的问题是你需要传入导致回发的控件的id,例如

 __doPostBack('btnPopup', null);

您可以在此问题中详细了解此功能:How to use __doPostBack()

答案 2 :(得分:0)

 $('.popup-window').click(function (e) {
data = '?sample=1' //serialized data here
callback    = function(json){
    if(json.returnVar!=true){ //check if returnVar is not true
        e.preventDefault();   //prevent redirect if not true
    }
};

$.ajax({
      type: 'POST',
      url: "../ajaxcall.php", //the url to call for ajax here
      data: data,
      success: callback,
      dataType: 'json'
    });
});

试试这个,如果您无法理解代码,请告诉我