簡體   English   中英

在調用JS函數之前對按鈕單擊進行驗證

[英]Verification on button click before calling JS function

好的,我知道單擊按鈕時如何要求驗證,但是我如何才能使它從單擊的同一按鈕中首先請求驗證,然后執行我想要的JS功能?

例如

function clicked(e)
{
    if(!confirm('Are you sure you want to do this?'))e.preventDefault();
}

<button type="button" onclick="clicked(event)">Close Round 1</button>

我要做的是在確認后調用以下函數,

function closer1() {...}

顯然沒有一個按鈕,我能以某種方式將按鈕的ID傳遞給所單擊的函數,然后以某種方式從那里調用該函數嗎?

出什么問題了

if(!confirm('Are you sure you want to do this?'))
{
   e.preventDefault();
   return false;
}
if(e=='button1') {
    closer1();
}
var result = confirm("Are you sure you want to do this?");
if (result == false) {
  e.preventDefault(); // user pressed cancel
} else {
  closer1(); // user pressed ok
}

如果您的可點擊按鈕共享一個功能,則您可以實施類似的操作,其結果取決於所點擊按鈕的ID

var result = confirm("Are you sure you want to do this?");
if (result == false) {
  e.preventDefault(); // user pressed cancel
} else if ($(this).attr('id') == 'button1') {
  closer1(); // user pressed ok, and request came from button 1
} else if ($(this).attr('id') == 'button2') {
  closer2(); // user pressed ok, and request came from button 2
}
function clicked(event, element)
{
   if(!confirm('Are you sure you want to do this?'))
   {
      e.preventDefault();
      return false;
   }

   // you can use 'element' as your element that has been clicked
}

<button type="button" onclick="clicked(event, this)">Close Round 1</button>

為什么不這樣做呢?

<button type="button" onclick="closer1()">Close Round 1</button>

如果那不是您想要的電話,那么您可以執行以下操作:

<button type="button" onclick="clicked('button1')">Close Round 1</button>

使用Javascript

function clicked(str){
   if(str=='button1')
      closer1();
   if(str=='button2')
      closer2();
   //and so on
}

這就是我要做的:


HTML:

<button type="button" onclick="sample_one(event)">Close Round 1</button>

JS:

function sample_one(e)
{
    e.preventDefault(); // Stops default action

    // Ask for confirmation
    if ( confirm('Are you sure you want to do this?') )
    {
        sample_two(); // Call the second defined function
    }
}

function sample_two()
{
    alert('sample_two function called.'); // Alert message to show defined function call
}

這是一個示例jsfiddle


function clicked(e){

   e.preventDefault();  

    var r = confirm("Are you sure you want to delete?");
    if (r == true) {

    } else { 
    return false;

    }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM