1

確認ボックスとして使用する関数を作成しました。

$.fn.confirmation = function(message, color) {

      $('.notification').css("background", color);
      $('.notification').html(message + "<br/><a href='#' id='sure'>I am sure</a> or <a href='#cancel' id='cancel'>Cancel</a>");
      $('.notification').slideDown();

      $(document).on("click", '.notification a', function(event){

        if($(this).attr("id") == "sure") {

          $('.notification').slideUp();

          return true;

        } else if($(this).attr("id") == "cancel") {

          $('.notification').slideUp();

          return false;
        }

      }); 

    };

私の問題は、常に false を返し、on イベントを待たないことです。

ユーザーがクリックするまでJQueryを強制的に待機させるにはどうすればよいですか?

4

4 に答える 4

1

return ステートメントは実際にはイベントが発生したときに実行される匿名関数にあり、関数には含まれていないため、 return ではありませfalseん。この問題を解決する最も簡単な方法 (私の意見では) は、オブジェクトを使用することです。undefinedconfirmationdeferred

$.fn.confirmation = function (message, color) {

    $('.notification').css("background", color);
    $('.notification').html(message + "<br/><a href='#' id='sure'>I am sure</a> or <a href='#cancel' id='cancel'>Cancel</a>");
    $('.notification').slideDown();

    var def = $.Deferred();

    $(document).on("click", '.notification a', function (event) {

        if ($(this).attr("id") == "sure") {

            $('.notification').slideUp();

            def.resolve(true);

        } else if ($(this).attr("id") == "cancel") {

            $('.notification').slideUp();

            def.resolve(false);
        }

    });

    return def.promise();
};


$.confirmation('message', 'red').done(function(result) {
   // result is true or false. 
});
于 2013-10-15T12:49:49.917 に答える
1

trueおよびfalseシナリオのコールバックを受け取るように、確認関数を変更する必要があります。

$.fn.confirmation = function(message, color, okCallback, cancelCallback) {
    $('.notification').css("background", color);
    $('.notification').html(message + "<br/><a href='#' id='sure'>I am sure</a> or <a href='#cancel' id='cancel'>Cancel</a>");
    $('.notification').slideDown();

    $(document).on("click", '.notification a', function(event){

      if($(this).attr("id") == "sure") {

        $('.notification').slideUp();

        okCallback();

    } else if($(this).attr("id") == "cancel") {

        $('.notification').slideUp();

        cancelCallback();
    }

  });         
}

次に、関数を呼び出すときに、匿名のコールバックを作成して、必要なことを行います。

$('#whatever').confirmation('...', '...', function() {
    //do 'OK' stuff
}, function() {
    //do 'Cancel' stuff
});
于 2013-10-15T12:50:48.893 に答える