2013-04-29 47 views
1

閱讀this question's answer暫停click事件,直至用戶輸入

後,我想知道如何構建的preventDefault/stopPropagation取決於用戶點擊的事件,例如:

<html> 
    <a data-handler="add_to_cart" data-item_id="5">Click</a> 
</html> 

點擊元素當前調用後端(通過ajax)將項目5添加到用戶手推車。但是,如果我想注入一個對話框第一(只有JavaScript)

var template = '' + 
    '<div class="dialog">' + 
     '<p>Really add this item?</p>' + 
     '<button>Yes</button>' + 
     '<button>No</button>' + 
    '</div>' 

$(a).click(function(){ 
    # open the dialog template 
    # if the correct button is clicked continue the default event 
}); 

我不想使用confirmprompt什麼,我基本上是在尋找一種方式用自己的HTML對話框來實現其功能。

+1

您應該使用'confirm',它是跨瀏覽器,可訪問的,並且可以在任何地方工作,包括移動設備。 – meagar 2013-04-29 13:36:23

回答

0

你有幾個選擇來實現這一點。我建議的兩個要麼覆蓋提示方法(關於覆蓋和更改外觀的see herehere),要麼創建自己的對話框並監視其上的按鈕。

重寫:

function prompt() { 
    //Insert your HTML, show the dialog 
} 

監視另一點擊:

$('#someOtherButton').click(function(){ 
    //Do what you want 
}); 

我建議乾脆重寫prompt()

0

您可以防止傳播並從對話框中重新調用click()方法,並要求傳播。

var template = '' + 
    '<div class="dialog">' + 
     '<p>Really add this item?</p>' + 
     '<button class=correctbutton>Yes</button>' + 
     '<button>No</button>' + 
    '</div>' 

$(a).click(function(){ 
    if(window.correctButtonClicked){ 
    return true;//continue propagation 
    } 
    window.clickedA=a // store current clicked object 
    openDialog() 
    return false; //stop propagation 
}); 

function openDialog(){ 
//Make a dialog from the template 
$('.correctbutton').click(function(){ 
     window.correctButtonClicked=true; 
     $(window.clickedA).click(); 
}); 

}