2014-09-21 44 views
-1

我做了我自己的,自制的,有/無功能,但它不起作用。jQuery確認/取消自制功能不起作用

下面是函數:

function CoverAndShow (title, text, type) { 
    if (type == "confirm") { 
     $("body").append("<div class='msg'><h3>" + title + "</h3><p>" + text + "</p><input class='ok' type='button' value='OK' /><input type='button' class='cancel' value='Cancel' /></div>"); 
    } 

    $(".ok").click(function() { 
     return true; 
    }); 

    $(".cancel").click(function() { 
     return false; 
    }); 
} 

這裏是我點擊「確定」,在功能代碼:

$("#ask").click(function() { 

    if (CoverAndShow("Title","Should I operate?", "confirm") == true) { 
     alert("true"); 
    } 

這將無法正常工作,並且不會返回任何東西。
幫助將不勝感激!

+0

哪部分不能工作? – 2014-09-21 09:06:19

+0

它應該是===真 – 2014-09-21 09:07:38

+1

==應該可以,只要你不需要檢查數據類型,不是嗎? – 2014-09-21 09:09:38

回答

4

你將需要在這裏使用回調。你不能從這種功能返回(查看asyncronity)。您將函數作爲最後一個參數傳遞給CoverAndShow,然後使用返回值調用它。

function CoverAndShow (title, text, type, callback) { 
 
    if (type == "confirm") { 
 
     $("body").append("<div class='msg'><h3>" + title + "</h3><p>" + text + "</p><input class='ok' type='button' value='OK' /><input type='button' class='cancel' value='Cancel' /></div>"); 
 
    } 
 

 
    $(".ok").click(function() { 
 
     callback(true); 
 
    }); 
 

 
    $(".cancel").click(function() { 
 
     callback(false); 
 
    }); 
 
} 
 

 
$("#ask").click(function() { 
 

 
    CoverAndShow("Title","Should I operate?", "confirm", function(ret){ 
 
     if (ret) { // no need to explicitly check for true 
 
     alert("true"); 
 
     } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="ask">ask</div>

+0

我得到一個「意外的令牌返回」錯誤,你可以擺弄嗎? – 2014-09-21 09:14:41

+1

已修復。我使用新的Stack Snippet功能爲您在答案中運行它。 :) – Scimonster 2014-09-21 09:21:29